我剛學春,現在約2周,並試圖瞭解一個概念庫,所以我還很陌生許多方面,但我會盡我所能解釋假設我有類:其迥異資源庫對象將被注入到參考
Product.java
class Product {
...
...
}
接口ProductRepository.java
public interface ProductRepository {
public List<Product> getAllProducts();
}
InMemoryProductRepository.java
@Repository
class InMemoryProductRepository implements ProductRepository{
....
....
}
productController.java
class productController{
@Autowired
private ProductRepository productRepository;
@RequestMapping("/products")
public String list(Model model) {
model.addAttribute("products", productRepository.getAllProducts());
return "products";
}
}
在我ProductController的就是我說的,
productRepository
不直接實施特定對象像productRepository = new InMemoryProductRepository();
,而不是productRepository
的標有@Autowired
因爲InMemoryProductRepository
有@Repository
所以InMemoryProductRepository
將被注入到這個productRepository
參考,但我的問題是,如果有另一個類誰實現了這個接口ProductRepository
並標有@Repository
也: 假設像
InMemoryProductRepository2.java
@Repository
class InMemoryProductRepository2 implements ProductRepository{
....
....
}
然後這兩個對象中的一個將被注入到
@Autowired
private ProductRepository productRepository;
?我如何區別它們?
謝謝,對不起,我的語言。
你想注入你的資料庫時使用'@ Qualifier'。看看這裏的答案,它可以幫助您與自動裝配理念:http://stackoverflow.com/a/19419296/1458983 – woemler
謝謝你讓我讀了 –