spring配置文件中bean name或者id相同所引起的問題

如果在spring的同一配置文件出現相同的id或name,會直接拋出異常,如果是在不同的配置文件中存在相同的id或name,那麼後面加載的bean會覆蓋前面的bean。

    id或name相同,但不屬於同一類型的bean,後面加載的bean也會覆蓋前面的bean:

這兩個bean是在不同的配置文件裏面,在加載spring容器的時候,第一個bean就會被覆蓋掉,這個時候自動注入Student類型的bean會報錯,

@Autowired()
private Student student;

報異常:No qualifying bean of type 'com.spring.entity.Student' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

他說沒有找到com.spring.entity.Student類型的bean,說明com.spring.entity.Student類型的bean已經被覆蓋了。

com.spring.entity.Action類型的bean是可以正常注入的。

 

如果在spring的配置文件中存在類型相同但name或id不同,那麼我們需要按名字注入這些bean:

1:
@Autowired()
private Student student;
@Autowired()
private Student student1;

這兩個實例分別對應上面兩個bean,對象名對應bean的name。

2:

除了這種方法還可以使用@Resource(name = "xxxx")註解按名字注入,

@Resource(name = "student")
 private Student student;

3:

@Autowired()也可以指定對應的bean:

@Autowired()
@Qualifier("bean名")
private Student student1;

其中@Resource是java的註解,@Autowired是spring的註解


 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章