本節主要內容:
1. 給MessageBean注入參數值
2. 測試Spring自動組件掃描方式
3. 如何控制ExampleBean實例化方式
4. 使用註解方式重構JdbcDataSource, UserDAO, UserService
javascript
本文做者:souvchtml
本文出處:http://www.cnblogs.com/liuhongfeng/p/4582664.html java
Spring能夠經過配置文件爲bean注入多種類型的屬性, MessageBean類用於演示Spring的多種類型數據的注入方式, 這些類型數據和注入方式包括:web
1. 注入基本值。spring
2. 注入Bean對象(請參考Unit 1案例)。express
3. 直接集合注入。bash
4. 引用方式集合注入app
5. 注入Spring表達式值。學習
6. 注入null或空字符串。測試
步驟一:新建工程,導入Spring API jar包
新建名爲SouvcSpringIoC_02的web工程,在該工程導入5個jar包。
commons-logging.jar
spring-core.jar
spring-context.jar
spring-beans.jar
spring-expression.jar
步驟二:新建Spring配置文件
在src目錄下,新建Spring配置文件applicationContext.xml。該文件名爲Spring默認的配置文件名,也能夠自由定義名稱。
applicationContext.xml文件中的代碼以下所示:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd"> </beans>
步驟三:新建類MessageBean 添加基本值屬性
新建類MessageBean,在該類中添加以下代碼中的四個屬性,並生成這幾個屬性對應的getter和setter方法;最後在execute方法獲取這幾個屬性的信息,代碼以下所示:
package com.souvc.bean; public class MessageBean { private String moduleName; private int pageSize; private String username; private String password = ""; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public String execute() { System.out.println("moduleName=" + moduleName); System.out.println("pageSize=" + pageSize); System.out.println("username=" + username); System.out.println("password=" + password); System.out.println("---List信息以下---"); return "success"; } }
步驟四:修改applicationContext.xml文件, 增長屬性基本值注入
修改applicationContext.xml文件,爲MessageBean的四個屬性注入基本參數值,代碼如圖-3所示:
<bean id="messagebean" class="com.souvc.bean.MessageBean">
<property name="moduleName" value="測試基本屬性"></property>
<property name="pageSize" value="5"></property>
<property name="username" value="daliu_it"></property>
<property name="password" value="123456"></property>
</bean>
步驟五:新建類Test1, 添加測試方法獲取MessageBean對象測試注入結果
新建類Test1,在類中使用ApplicationContext的方式實例化Spring容器,獲取MessageBean對象,並調用execute方法。
@Test public void test1() { String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); System.out.println(ac); MessageBean messagebean = ac.getBean("messagebean", MessageBean.class); System.out.println(messagebean.toString()); messagebean.execute(); }
步驟六:運行Test1類, 測試注入結果
運行Test1類,控制檯輸入結果
org.springframework.context.support.ClassPathXmlApplicationContext@65b4fad5: startup date [Wed Jun 17 11:16:13 CST 2015]; root of context hierarchy com.souvc.bean.MessageBean@5d3e754f moduleName=測試基本屬性 pageSize=5 username=daliu_it password=123456 ---List信息以下---
控制檯輸出所示的信息,說明獲取到了注入的基本屬性值。
步驟七:爲MessageBean添加集合屬性,用於注入集合測試
1. 修改類MessageBean,在該類中添加以下加粗代碼中的四個屬性,並生成這幾個屬性對應的getter和setter方法;最後在execute方法獲取這幾個屬性的信息,代碼以下所示:
package com.souvc.bean; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class MessageBean { private String moduleName; private int pageSize; private String username; private String password = ""; private List<String> someList; private Set<String> someSet; private Map<String,Object> someMap; private Properties someProps; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public List<String> getSomeList() { return someList; } public void setSomeList(List<String> someList) { this.someList = someList; } public Set<String> getSomeSet() { return someSet; } public void setSomeSet(Set<String> someSet) { this.someSet = someSet; } public Map<String, Object> getSomeMap() { return someMap; } public void setSomeMap(Map<String, Object> someMap) { this.someMap = someMap; } public Properties getSomeProps() { return someProps; } public void setSomeProps(Properties someProps) { this.someProps = someProps; } public String execute() { System.out.println("moduleName=" + moduleName); System.out.println("pageSize=" + pageSize); System.out.println("username=" + username); System.out.println("password=" + password); System.out.println("---List信息以下---"); for(String s : someList){ System.out.println(s); } System.out.println("---Set信息以下---"); for(String s : someSet){ System.out.println(s); } System.out.println("---Map信息以下---"); Set<String> keys = someMap.keySet(); for(String key : keys){ System.out.println(key+"=" +someMap.get(key)); } System.out.println("---Properties信息以下---"); Set<Object> keys1 = someProps.keySet(); for(Object key : keys1){ System.out.println(key+"=" +someProps.getProperty(key.toString())); } return "success"; } }
2. 修改applicationContext.xml文件,爲MessageBean的四個屬性注入集合參數值:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!-- 加載properties文件爲bean <util:properties id="jdbcProperties" location="classpath:db.properties" /> --> <bean id="messagebean" class="com.souvc.bean.MessageBean"> <property name="moduleName" value="測試基本屬性的注入"></property> <property name="pageSize" value="5"></property> <!-- 表達式注入 --> <property name="username" value="daliu_it"></property> <property name="password" value="123456"></property> <property name="someList"> <list> <value>北京</value> <value>上海</value> <value>廣州</value> </list> </property> <property name="someSet"> <set> <value>James Gosling</value> <value>Martin fowler</value> <value>Larry Ellision</value> </set> </property> <property name="someMap"> <map> <entry key="1001" value="Java語言基礎"></entry> <entry key="1002" value="Java Web基礎"></entry> <entry key="1003" value="Spring使用基礎"></entry> </map> </property> <property name="someProps"> <props> <prop key="username">root</prop> <prop key="password">1234</prop> </props> </property> </bean> <!-- 定義集合Bean <util:list id="oneList"> <value>Tom</value> <value>Andy</value> </util:list> <util:set id="oneSet"> <value>James Gosling</value> <value>Martin fowler</value> </util:set> <util:map id="oneMap"> <entry key="1001" value="Java語言基礎"></entry> <entry key="1002" value="Java Web基礎"></entry> </util:map> <util:properties id="oneProps"> <prop key="username">root</prop> <prop key="password">1234</prop> </util:properties> --> <!-- 引用方式注入集合屬性 <bean id="messagebean2" class="com.souvc.bean.MessageBean"> <property name="moduleName" value="資費管理"></property> <property name="pageSize" value="5"></property> <property name="username" value="andy"></property> <property name="password" value="123"></property>--> <!-- 引用方式注入集合屬性 <property name="someList" ref="oneList" /> <property name="someSet" ref="oneSet" /> <property name="someMap" ref="oneMap" /> <property name="someProps" ref="oneProps" /> </bean>--> </beans>
3. 運行Test1類,控制檯輸出結果所示:
org.springframework.context.support.ClassPathXmlApplicationContext@42704baa: startup date [Wed Jun 17 11:30:43 CST 2015]; root of context hierarchy com.souvc.bean.MessageBean@25961581 moduleName=測試基本屬性的注入 pageSize=5 username=daliu_it password=123456 ---List信息以下--- 北京 上海 廣州 ---Set信息以下--- James Gosling Martin fowler Larry Ellision ---Map信息以下--- 1001=Java語言基礎 1002=Java Web基礎 1003=Spring使用基礎 ---Properties信息以下--- password=1234 username=root
控制檯輸出的信息,說明只須要經過配置Spring就能夠爲Bean注入集合參數值。
步驟八:測試引用方式集合注入
1.爲Spring配置文件applicationContext.xml增長以下配置, 採用引用方式注入集合對象, 代碼參考以下:
<!-- 定義集合Bean -->
<util:list id="oneList">
<value>Tom</value>
<value>Andy</value>
</util:list>
<util:set id="oneSet">
<value>James Gosling</value>
<value>Martin fowler</value>
</util:set>
<util:map id="oneMap">
<entry key="1001" value="Java語言基礎"></entry>
<entry key="1002" value="Java Web基礎"></entry>
</util:map>
<util:properties id="oneProps">
<prop key="username">root</prop>
<prop key="password">1234</prop>
</util:properties>
<!-- 引用方式注入集合屬性 -->
<bean id="messagebean2" class="com.souvc.bean.MessageBean">
<property name="moduleName" value="資費管理"></property>
<property name="pageSize" value="5"></property>
<property name="username" value="andy"></property>
<property name="password" value="123"></property>
<!-- 引用方式注入集合屬性 -->
<property name="someList" ref="oneList" />
<property name="someSet" ref="oneSet" />
<property name="someMap" ref="oneMap" />
<property name="someProps" ref="oneProps" />
</bean>
2. 增長Test2類測試如上配置, Test2代碼以下:
package com.souvc.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.souvc.bean.MessageBean; public class TestCase { @Test public void test1() { String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); System.out.println(ac); MessageBean messagebean = ac.getBean("messagebean", MessageBean.class); System.out.println(messagebean.toString()); messagebean.execute(); } @Test public void test2() { String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); MessageBean bean = ac.getBean("messagebean2", MessageBean.class); bean.execute(); } }
3. 執行Test2 有以下結果所示:
moduleName=資費管理 pageSize=5 username=andy password=123 ---List信息以下--- Tom Andy ---Set信息以下--- James Gosling Martin fowler ---Map信息以下--- 1001=Java語言基礎 1002=Java Web基礎 ---Properties信息以下--- password=1234 username=root
這個結果說明, 經過引用方式也能夠爲bean注入集合屬性.
步驟九:利用 Spring表達式注入屬性值
1.在工程的src下,新建屬性文件db.properties,文件內容以下:
user=scott
2. 修改applicationContext.xml文件,注入Spring表達式值,代碼所示:
<!-- 加載properties文件爲bean --> <util:properties id="jdbcProperties" location="classpath:db.properties" /> <bean id="messagebean" class="org.tarena.bean.MessageBean"> <!-- ================================================================ --> <property name="moduleName" value="資費管理"></property> <property name="pageSize" value="5"></property> <!-- 表達式注入 --> <property name="username" value="#{jdbcProperties.user}"></property> <property name="password"> <null /> </property>
3. 運行Test1類,控制檯輸出結果所示:
org.springframework.context.support.ClassPathXmlApplicationContext@68861f24: startup date [Wed Jun 17 11:41:35 CST 2015]; root of context hierarchy com.souvc.bean.MessageBean@209444d1 moduleName=測試基本屬性的注入 pageSize=5 username=daliu_it password=123456 ---List信息以下--- 北京 上海 廣州 ---Set信息以下--- James Gosling Martin fowler Larry Ellision ---Map信息以下--- 1001=Java語言基礎 1002=Java Web基礎 1003=Spring使用基礎 ---Properties信息以下--- password=1234 username=root
控制檯輸出信息,說明獲取到了注入的Spring表達式值。
步驟十:注入null值
1. 修改applicationContext.xml文件,將屬性password注入null值,代碼如圖-11所示:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!-- 加載properties文件爲bean--> <util:properties id="jdbcProperties" location="classpath:db.properties" /> <bean id="messagebean" class="com.souvc.bean.MessageBean"> <property name="moduleName" value="測試基本屬性的注入"></property> <property name="pageSize" value="5"></property> <!-- 表達式注入 <property name="username" value="daliu_it"></property>--> <property name="username" value="#{jdbcProperties.user}"></property> <property name="password" > <null/> </property> <property name="someList"> <list> <value>北京</value> <value>上海</value> <value>廣州</value> </list> </property> <property name="someSet"> <set> <value>James Gosling</value> <value>Martin fowler</value> <value>Larry Ellision</value> </set> </property> <property name="someMap"> <map> <entry key="1001" value="Java語言基礎"></entry> <entry key="1002" value="Java Web基礎"></entry> <entry key="1003" value="Spring使用基礎"></entry> </map> </property> <property name="someProps"> <props> <prop key="username">root</prop> <prop key="password">1234</prop> </props> </property> </bean> <!-- 定義集合Bean --> <util:list id="oneList"> <value>Tom</value> <value>Andy</value> </util:list> <util:set id="oneSet"> <value>James Gosling</value> <value>Martin fowler</value> </util:set> <util:map id="oneMap"> <entry key="1001" value="Java語言基礎"></entry> <entry key="1002" value="Java Web基礎"></entry> </util:map> <util:properties id="oneProps"> <prop key="username">root</prop> <prop key="password">1234</prop> </util:properties> <!-- 引用方式注入集合屬性 --> <bean id="messagebean2" class="com.souvc.bean.MessageBean"> <property name="moduleName" value="資費管理"></property> <property name="pageSize" value="5"></property> <property name="username" value="andy"></property> <property name="password" value="123"></property> <!-- 引用方式注入集合屬性 --> <property name="someList" ref="oneList" /> <property name="someSet" ref="oneSet" /> <property name="someMap" ref="oneMap" /> <property name="someProps" ref="oneProps" /> </bean> </beans>
2. 運行Test1類,控制檯輸出結果:
org.springframework.context.support.ClassPathXmlApplicationContext@2996c1b0: startup date [Wed Jun 17 11:42:47 CST 2015]; root of context hierarchy com.souvc.bean.MessageBean@195ed659 moduleName=測試基本屬性的注入 pageSize=5 username=daliu_it password=null ---List信息以下--- 北京 上海 廣州 ---Set信息以下--- James Gosling Martin fowler Larry Ellision ---Map信息以下--- 1001=Java語言基礎 1002=Java Web基礎 1003=Spring使用基礎 ---Properties信息以下--- password=1234 username=root
控制檯輸出所示的信息,說明獲取到了注入的null值。
MessageBean類的完整代碼以下所示:
package com.souvc.bean; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class MessageBean { private String moduleName; private int pageSize; private String username; private String password = ""; private List<String> someList; private Set<String> someSet; private Map<String, Object> someMap; private Properties someProps; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getModuleName() { return moduleName; } public void setModuleName(String moduleName) { this.moduleName = moduleName; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public List<String> getSomeList() { return someList; } public void setSomeList(List<String> someList) { this.someList = someList; } public Set<String> getSomeSet() { return someSet; } public void setSomeSet(Set<String> someSet) { this.someSet = someSet; } public Map<String, Object> getSomeMap() { return someMap; } public void setSomeMap(Map<String, Object> someMap) { this.someMap = someMap; } public Properties getSomeProps() { return someProps; } public void setSomeProps(Properties someProps) { this.someProps = someProps; } public String execute() { System.out.println("moduleName=" + moduleName); System.out.println("pageSize=" + pageSize); System.out.println("username=" + username); System.out.println("password=" + password); System.out.println("---List信息以下---"); for (String s : someList) { System.out.println(s); } System.out.println("---Set信息以下---"); for (String s : someSet) { System.out.println(s); } System.out.println("---Map信息以下---"); Set<String> keys = someMap.keySet(); for (String key : keys) { System.out.println(key + "=" + someMap.get(key)); } System.out.println("---Properties信息以下---"); Set<Object> keys1 = someProps.keySet(); for (Object key : keys1) { System.out.println(key + "=" + someProps.getProperty(key.toString())); } return "success"; } }
Test1,Test2的完整代碼以下:
package com.souvc.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.souvc.bean.MessageBean; public class TestCase { @Test public void test1() { String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); System.out.println(ac); MessageBean messagebean = ac.getBean("messagebean", MessageBean.class); System.out.println(messagebean.toString()); messagebean.execute(); } @Test public void test2() { String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); MessageBean bean = ac.getBean("messagebean2", MessageBean.class); bean.execute(); } }
applicationContext.xml完整代碼以下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!-- 加載properties文件爲bean--> <util:properties id="jdbcProperties" location="classpath:db.properties" /> <bean id="messagebean" class="com.souvc.bean.MessageBean"> <property name="moduleName" value="測試基本屬性的注入"></property> <property name="pageSize" value="5"></property> <!-- 表達式注入 <property name="username" value="daliu_it"></property>--> <property name="username" value="#{jdbcProperties.user}"></property> <property name="password" > <null/> </property> <property name="someList"> <list> <value>北京</value> <value>上海</value> <value>廣州</value> </list> </property> <property name="someSet"> <set> <value>James Gosling</value> <value>Martin fowler</value> <value>Larry Ellision</value> </set> </property> <property name="someMap"> <map> <entry key="1001" value="Java語言基礎"></entry> <entry key="1002" value="Java Web基礎"></entry> <entry key="1003" value="Spring使用基礎"></entry> </map> </property> <property name="someProps"> <props> <prop key="username">root</prop> <prop key="password">1234</prop> </props> </property> </bean> <!-- 定義集合Bean --> <util:list id="oneList"> <value>Tom</value> <value>Andy</value> </util:list> <util:set id="oneSet"> <value>James Gosling</value> <value>Martin fowler</value> </util:set> <util:map id="oneMap"> <entry key="1001" value="Java語言基礎"></entry> <entry key="1002" value="Java Web基礎"></entry> </util:map> <util:properties id="oneProps"> <prop key="username">root</prop> <prop key="password">1234</prop> </util:properties> <!-- 引用方式注入集合屬性 --> <bean id="messagebean2" class="com.souvc.bean.MessageBean"> <property name="moduleName" value="資費管理"></property> <property name="pageSize" value="5"></property> <property name="username" value="andy"></property> <property name="password" value="123"></property> <!-- 引用方式注入集合屬性 --> <property name="someList" ref="oneList" /> <property name="someSet" ref="oneSet" /> <property name="someMap" ref="oneMap" /> <property name="someProps" ref="oneProps" /> </bean> </beans>
源碼以下:http://yunpan.cn/cQVU3sLcMzXGC 訪問密碼 daf3
如何使用組件掃描的方式和"註解標記"配合獲取容器中的ExampleBean對象。
使用組件掃描,首先須要在XML配置中指定掃描類路徑,配置代碼以下:
<context:component-scan base-package="com.souvc"/>
上述配置,容器實例化時會自動掃描com.souvc 包及其子包下全部組件類。
指定掃描類路徑後,並非該路徑下全部組件類都掃描到Spring容器的,只有在組件類定義前面有如下註解標記時,纔會掃描到Spring容器。
@Component 泛指組件,當組件很差歸類的時候,咱們可使用這個註解進行標註。
@Name 通用註解
@Service 業務層組件註解, 用於標註業務層組件
@Repository 持久層組件註解,用於標註數據訪問組件,即DAO組件
@Controller 控制層組件註解,用於標註控制層組件(如struts中的action)
步驟一:新建類ExampleBean
新建類ExampleBean,在該類前使用通用組件註解「@Component」,代表ExampleBean爲可被掃描的組件,代碼以下所示:
package com.souvc.bean; import org.springframework.stereotype.Component; @Component public class ExampleBean { public ExampleBean() { System.out.println("實例化ExampleBean"); } public void execute() { System.out.println("執行ExampleBean處理"); } }
步驟二: 修改applicationContext.xml
修改applicationContext.xml,使容器實例化時自動掃描org.tarena包及其子包下全部組件類
<!-- 組件掃描 -->
<context:component-scan base-package="com.souvc" />
步驟三: 新建方法Test3
@Test public void test3() { String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); ExampleBean bean = ac.getBean("exampleBean", ExampleBean.class); bean.execute(); }
運行Test3方法,控制檯輸出結果:
控制檯輸出上述結果,說明Spring會自動使用組件掃描的方式建立ExampleBean實例, 而且Test3中獲取到了這個ExampleBean對象。
ExampleBean類的完整代碼以下所示:
package com.souvc.bean; import org.springframework.stereotype.Component; @Component public class ExampleBean { public ExampleBean() { System.out.println("實例化ExampleBean"); } public void execute() { System.out.println("執行ExampleBean處理"); } }
TestCase 類的完整代碼以下所示:
package com.souvc.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.souvc.bean.ExampleBean; import com.souvc.bean.MessageBean; public class TestCase { @Test public void test1() { String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); System.out.println(ac); MessageBean messagebean = ac.getBean("messagebean", MessageBean.class); System.out.println(messagebean.toString()); messagebean.execute(); } @Test public void test2() { String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); MessageBean bean = ac.getBean("messagebean2", MessageBean.class); bean.execute(); } @Test public void test3() { String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); ExampleBean bean = ac.getBean("exampleBean", ExampleBean.class); bean.execute(); } }
applicationContext.xml文件的完整代碼以下所示:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!-- 加載properties文件爲bean--> <util:properties id="jdbcProperties" location="classpath:db.properties" /> <bean id="messagebean" class="com.souvc.bean.MessageBean"> <property name="moduleName" value="測試基本屬性的注入"></property> <property name="pageSize" value="5"></property> <!-- 表達式注入 <property name="username" value="daliu_it"></property>--> <property name="username" value="#{jdbcProperties.user}"></property> <property name="password"> <null /> </property> <property name="someList"> <list> <value>北京</value> <value>上海</value> <value>廣州</value> </list> </property> <property name="someSet"> <set> <value>James Gosling</value> <value>Martin fowler</value> <value>Larry Ellision</value> </set> </property> <property name="someMap"> <map> <entry key="1001" value="Java語言基礎"></entry> <entry key="1002" value="Java Web基礎"></entry> <entry key="1003" value="Spring使用基礎"></entry> </map> </property> <property name="someProps"> <props> <prop key="username">root</prop> <prop key="password">1234</prop> </props> </property> </bean> <!-- 定義集合Bean --> <util:list id="oneList"> <value>Tom</value> <value>Andy</value> </util:list> <util:set id="oneSet"> <value>James Gosling</value> <value>Martin fowler</value> </util:set> <util:map id="oneMap"> <entry key="1001" value="Java語言基礎"></entry> <entry key="1002" value="Java Web基礎"></entry> </util:map> <util:properties id="oneProps"> <prop key="username">root</prop> <prop key="password">1234</prop> </util:properties> <!-- 引用方式注入集合屬性 --> <bean id="messagebean2" class="com.souvc.bean.MessageBean"> <property name="moduleName" value="資費管理"></property> <property name="pageSize" value="5"></property> <property name="username" value="andy"></property> <property name="password" value="123"></property> <!-- 引用方式注入集合屬性 --> <property name="someList" ref="oneList" /> <property name="someSet" ref="oneSet" /> <property name="someMap" ref="oneMap" /> <property name="someProps" ref="oneProps" /> </bean> <!-- 組件掃描 --> <context:component-scan base-package="com.souvc" /> </beans>
使用組件掃描的方式,重構如何控制ExampleBean實例化爲單例或非單例模式。
1. 一般受Spring管理的組件,默認的做用域是"singleton"。若是須要其餘的做用域可使用@Scope註解,只要在註解中提供做用域的名稱便可,代碼以下:
@Component @Scope("singleton") public class ExampleBean { ... }
2. @PostConstruct和@PreDestroy註解標記分別用於指定初始化和銷燬回調方法,代碼以下:
public class ExampleBean { @PostConstruct public void init() { //初始化回調方法 } @PreDestroy public void destroy() { //銷燬回調方法 } }
步驟一:Bean對象的建立模式
1. 修改ExampleBean,使用prototype模式建立 ExampleBean 對象,修改的代碼:
package com.souvc.bean; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("prototype") public class ExampleBean { public ExampleBean() { System.out.println("實例化ExampleBean"); } // public void execute() { // System.out.println("執行ExampleBean處理"); // } // // @PostConstruct // public void init() { // System.out.println("初始化ExampleBean對象"); // } // // @PreDestroy // public void destroy() { // System.out.println("銷燬ExampleBean對象"); // } }
2. 新建類Test4在該類中建立兩個ExampleBean對象,經過比較操做符==進行比較,代碼如圖-19所示:
@Test public void test4() { String conf = "applicationContext.xml"; AbstractApplicationContext ac = new ClassPathXmlApplicationContext(conf); ExampleBean bean1 = ac.getBean("exampleBean", ExampleBean.class); ExampleBean bean2 = ac.getBean("exampleBean", ExampleBean.class); System.out.println(bean1 == bean2); ac.close(); }
3. 運行Test4,控制檯輸出結果以下:
實例化ExampleBean 實例化ExampleBean false
經過前面的講解,瞭解到默認狀況下Spring容器是經過單例模式建立Bean對象的。經過本案例的運行結果,能夠看出使用原型方式,調用了2次ExampleBean類的構造方法,說明建立了2個ExampleBean對象。
4. 若是想要使用單例模式建立對象,也可使用註解的方式進行顯示標註,修改ExampleBean類的代碼所示:
package com.souvc.bean; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component //@Scope("prototype") @Scope("singleton") public class ExampleBean { public ExampleBean() { System.out.println("實例化ExampleBean"); } // public void execute() { // System.out.println("執行ExampleBean處理"); // } // // @PostConstruct // public void init() { // System.out.println("初始化ExampleBean對象"); // } // // @PreDestroy // public void destroy() { // System.out.println("銷燬ExampleBean對象"); // } }
5. 再次運行Test4,控制檯輸出結果以下:
實例化ExampleBean true
上述運行結果能夠看得出,兩個ExampleBean對象,經過比較操做符「 ==」進行比較的輸出結果爲true,說明Spring容器是經過單例模式建立Bean對象的。
步驟二:Bean對象的初始化和銷燬
1. 修改ExampleBean類,加入方法init和方法destroy,並使用註解「@PostConstruct」和註解「@PreDestroy」指定init爲初始化的回調方法、destroy爲銷燬的回調方法,代碼以下所示:
package com.souvc.bean; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component //@Scope("prototype") @Scope("singleton") public class ExampleBean { public ExampleBean() { System.out.println("實例化ExampleBean"); } public void execute() { System.out.println("執行ExampleBean處理"); } @PostConstruct public void init() { System.out.println("初始化ExampleBean對象"); } @PreDestroy public void destroy() { System.out.println("銷燬ExampleBean對象"); } }
2.運行Test4類,控制檯輸出結果所示:
實例化ExampleBean 初始化ExampleBean對象 true 2015-6-17 14:26:05 org.springframework.context.support.AbstractApplicationContext doClose 信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@45b9ce4b: startup date [Wed Jun 17 14:26:04 CST 2015]; root of context hierarchy 2015-6-17 14:26:05 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons 信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@36f0b7f8: defining beans [jdbcProperties,messagebean,oneList,oneSet,oneMap,oneProps,messagebean2,exampleBean,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy 銷燬ExampleBean對象
控制檯輸出了「初始化ExampleBean對象」和「銷燬ExampleBean對象」,說明使用組件掃描的方式爲ExampleBean類添加初始化和銷燬的回調方法成功。
ExampleBean類的完整代碼以下所示:
package com.souvc.bean; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component //@Scope("prototype") @Scope("singleton") public class ExampleBean { public ExampleBean() { System.out.println("實例化ExampleBean"); } public void execute() { System.out.println("執行ExampleBean處理"); } @PostConstruct public void init() { System.out.println("初始化ExampleBean對象"); } @PreDestroy public void destroy() { System.out.println("銷燬ExampleBean對象"); } }
Test4類的完整代碼以下所示:
package com.souvc.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.souvc.bean.ExampleBean; import com.souvc.bean.MessageBean; public class TestCase { @Test public void test1() { String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); System.out.println(ac); MessageBean messagebean = ac.getBean("messagebean", MessageBean.class); System.out.println(messagebean.toString()); messagebean.execute(); } @Test public void test2() { String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); MessageBean bean = ac.getBean("messagebean2", MessageBean.class); bean.execute(); } @Test public void test3() { String conf = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(conf); ExampleBean bean = ac.getBean("exampleBean", ExampleBean.class); //bean.execute(); } @Test public void test4() { String conf = "applicationContext.xml"; AbstractApplicationContext ac = new ClassPathXmlApplicationContext(conf); ExampleBean bean1 = ac.getBean("exampleBean", ExampleBean.class); ExampleBean bean2 = ac.getBean("exampleBean", ExampleBean.class); System.out.println(bean1 == bean2); ac.close(); } }
applicationContext.xml文件的完整代碼與前一案例相同。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <!-- 加載properties文件爲bean--> <util:properties id="jdbcProperties" location="classpath:db.properties" /> <bean id="messagebean" class="com.souvc.bean.MessageBean"> <property name="moduleName" value="測試基本屬性的注入"></property> <property name="pageSize" value="5"></property> <!-- 表達式注入 <property name="username" value="daliu_it"></property>--> <property name="username" value="#{jdbcProperties.user}"></property> <property name="password"> <null /> </property> <property name="someList"> <list> <value>北京</value> <value>上海</value> <value>廣州</value> </list> </property> <property name="someSet"> <set> <value>James Gosling</value> <value>Martin fowler</value> <value>Larry Ellision</value> </set> </property> <property name="someMap"> <map> <entry key="1001" value="Java語言基礎"></entry> <entry key="1002" value="Java Web基礎"></entry> <entry key="1003" value="Spring使用基礎"></entry> </map> </property> <property name="someProps"> <props> <prop key="username">root</prop> <prop key="password">1234</prop> </props> </property> </bean> <!-- 定義集合Bean --> <util:list id="oneList"> <value>Tom</value> <value>Andy</value> </util:list> <util:set id="oneSet"> <value>James Gosling</value> <value>Martin fowler</value> </util:set> <util:map id="oneMap"> <entry key="1001" value="Java語言基礎"></entry> <entry key="1002" value="Java Web基礎"></entry> </util:map> <util:properties id="oneProps"> <prop key="username">root</prop> <prop key="password">1234</prop> </util:properties> <!-- 引用方式注入集合屬性 --> <bean id="messagebean2" class="com.souvc.bean.MessageBean"> <property name="moduleName" value="資費管理"></property> <property name="pageSize" value="5"></property> <property name="username" value="andy"></property> <property name="password" value="123"></property> <!-- 引用方式注入集合屬性 --> <property name="someList" ref="oneList" /> <property name="someSet" ref="oneSet" /> <property name="someMap" ref="oneMap" /> <property name="someProps" ref="oneProps" /> </bean> <!-- 組件掃描 --> <context:component-scan base-package="com.souvc" /> </beans>
本文做者:souvc