例如:serviceImpl implements Interface1,Interface2
在controller中
@Autowired Interface1
只能調用 Interface1接口的方法
總結,注入單個接口,只能調用對應的接口方法
2、一個接口多個實現類,注入指定的實現類
例如:Interface 接口有兩個實現類 InterfaceImpl1 和 InterfaceImpl2
//實現類1
@Service
public class InterfaceImpl1 implements Interface {
//實現類1
@Service
public class InterfaceImpl2implements Interface {
//業務類,controller
@Autowired Interface
private Interface interface;
按照上面的寫法,啓動服務時會報錯
解決方法
1.指明實現類的優先級,注入的時候使用優先級高的實現類
//實現類1
@Service
@Primary //同一個接口的實現類,最多隻能有一個添加該註解
public class InterfaceImpl1 implements Interface {
在controller中注入接口,默認使用的是Primary 標註的實現類的方法
2.通過 @Autowired 和 @Qualifier 配合注入
@Autowired
@Qualifier("interfaceImpl1")
Interface1 interface1; //正常啓動
3.使用@Resource注入,根據默認類名區分
@Resource(name = "interfaceImpl1")
Interface1 interface1; //正常啓動
4.使用@Resource注入,根據@Service指定的名稱區分
需要在實現類@Service後設置名稱:
@Service("s1")
public class InterfaceImpl1 implements Interface {
@Resource(name = "s1")
Interface1 interface1; //正常啓動
spring常用註解說明
- @Configuration把一個類作爲一個IoC容器,它的某個方法頭上如果註冊了@Bean,就會作爲這個Spring容器中的Bean。
- @Scope註解 作用域
- @Lazy(true) 表示延遲初始化
- @Service用於標註業務層組件、
- @Controller用於標註控制層組件(如struts中的action)
- @Repository用於標註數據訪問組件,即DAO組件。
- @Component泛指組件,當組件不好歸類的時候,我們可以使用這個註解進行標註。
- @Scope用於指定scope作用域的(用在類上)
- @PostConstruct用於指定初始化方法(用在方法上)
- @PreDestory用於指定銷燬方法(用在方法上)
- @Resource 默認按名稱裝配,當找不到與名稱匹配的bean纔會按類型裝配。
- @DependsOn:定義Bean初始化及銷燬時的順序
- @Primary:自動裝配時當出現多個Bean候選者時,被註解爲@Primary的Bean將作爲首選者,否則將拋出異常
- @Autowired 默認按類型裝配,如果我們想使用按名稱裝配,可以結合@Qualifier註解一起使用
- @Autowired @Qualifier("personDaoBean") 存在多個實例配合使用