2015-08-21 49 views
0

我剛學春,現在約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; 

?我如何區別它們?

謝謝,對不起,我的語言。

+0

你想注入你的資料庫時使用'@ Qualifier'。看看這裏的答案,它可以幫助您與自動裝配理念:http://stackoverflow.com/a/19419296/1458983 – woemler

+0

謝謝你讓我讀了 –

回答

1

如果有這樣的情況,你會給名到每個執行豆@Repository(「名稱」),並使用@Qualifier(「名稱」)批註與@Autowired。

+0

太謝謝你了約翰 –

+0

沒問題漢斯:) – John