前言
Spring框架對Bean進行裝配提供了很靈活的方式卸耘,下面歸納一下主要的方式:
? 在XML中進行顯示配置
? 在Java中進行顯示配置
? 隱式的bean發(fā)現(xiàn)機制和自動裝配
而自動裝配實現(xiàn)就需要注解掃描泣刹,這時發(fā)現(xiàn)了兩種開啟注解掃描的方式场航,即<context:annotation-config/>
和<context:component-scan>
下面歸納一下這兩種方式的異同點:
<context:annotation-config>
:注解掃描是針對已經(jīng)在Spring容器里注冊過的Bean
<context:component-scan>
:不僅具備<context:annotation-config>
的所有功能九妈,還可以在指定的package下面掃描對應(yīng)的bean
Demo:
Demo:XML注冊Bean方式
下面給出兩個類凯楔,類A和類B
package com.test;
pubic class B{
public B(){
System.out.println("B類");
}
}
package com.test;
public class A {
private B bClass;
public void setBClass(B bClass){
this.bClass = bClass;
System.out.println("通過set的方式注入B類");
}
public A(){
System.out.println("A類");
}
}
如何我們這時可以通過傳統(tǒng)的xml配置在Application.xml里進行bean注冊
<bean id="bBean"class="com.test.B"/>
<bean id="aBean"class="com.test.A">
<property name="bClass" ref="bBean"/>
</bean>
啟動加載Application.xml
輸出:
類B
類A
通過set的方式注入B類
Demo:annotation配置注解開啟方式
package com.test;
pubic class B{
public B(){
System.out.println("B類");
}
}
package com.test;
public class A {
private B bClass;
@Autowired
public void setBClass(B bClass){
this.bClass = bClass;
System.out.println("通過set的方式注入B類");
}
public A(){
System.out.println("A類");
}
}
然后我們需要在Application.xml里注冊Bean哪审,假如我們先這樣配置饶深,僅僅注冊Bean餐曹,不開啟掃描
<bean id="bBean"class="com.test.B"/>
<bean id="aBean"class="com.test.A"/>
或者僅僅開啟掃描,不注冊Bean
<context:annotation-config/>
這時加載Application.xml配置
輸出:
類B
類A
我們會發(fā)現(xiàn)下面的@Autowired的方法是不能被加載的
@Autowired
public void setBClass(B bClass){
this.bClass = bClass;
System.out.println("通過set的方式注入B類");
}
解決方法:
修改Application.xml配置文件
<context:annotation-config/>
<bean id="bBean"class="com.test.B"/>
<bean id="aBean"class="com.test.A"/>
重新加載配置文件敌厘,輸出正常了
輸出:
類B
類A
通過set的方式注入B類
歸納:<context:annotation-config>
:注解掃描是針對已經(jīng)在Spring容器里注冊過的Bean
Demo:component配置注解開啟方式
package com.test;
pubic class B{
public B(){
System.out.println("B類");
}
}
package com.test;
@Component
public class A {
private B bClass;
@Autowired
public void setBClass(B bClass){
this.bClass = bClass;
System.out.println("通過set的方式注入B類");
}
public A(){
System.out.println("A類");
}
}
然后我們配置一下application.xml台猴,開啟annotaion-config掃描
<context:annotation-config />
加載配置文件:
輸出:
類B
類A
原因:<context:annotation-config>
:注解掃描是針對已經(jīng)在Spring容器里注冊過的Bean,Bean并沒有注冊過俱两,所以即使開啟了@Autowired饱狂、@Component注解 和配置開啟了annotaion-config掃描還是加載不到
修改配置文件:
<context:component-scan base-package="com.test"/>
重新加載配置文件:
輸出:
類B
類A
通過set的方式注入B類
歸納:
<context:annotation-config>
:注解掃描是針對已經(jīng)在Spring容器里注冊過的Bean
<context:component-scan>
:不僅具備<context:annotation-config>
的所有功能,還可以在指定的package下面掃描對應(yīng)的bean
<context:annotation-config />
和<context:component-scan>
同時存在的時候宪彩,前者會被忽略休讳。
即使注冊Bean,同時開啟
<context:annotation-config />
掃描尿孔,@autowire俊柔,@resource等注入注解只會被注入一次,也即只加載一次