Spring架構第二篇之Bean的裝配,spring第二篇bean
一、預設裝配方式
代碼通過getBean();方式從容器中擷取指定的Bean執行個體,容器首先會調用Bean類的無參構造器,建立空值的執行個體對象。
舉例:
首先我在applicationContext.xml設定檔中配置了一個bean:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 註冊Service 這裡相當於容器做了SomeServiceImpl myService = new SomeServiceImpl(); --> <bean id="myService" class="com.ietree.spring.basic.ioc.SomeServiceImpl"/> </beans>
建立SomeServiceImpl對象,但需要注意的是該類的只具有帶參構造函器,沒有無參構造器:
package com.ietree.spring.basic.ioc;/** * 實作類別 * * @author Root */public class SomeServiceImpl implements ISomeService { private int a; // 這裡注釋掉了無參建構函式,希望容器通過帶參建構函式建立對象// public SomeServiceImpl() {// System.out.println("執行無參構造器,建立SomeServiceImpl對象");// } public SomeServiceImpl(int a) { this.a = a; } @Override public void doSomeThing() { System.out.println("執行doSomeThing()方法..."); }}
測試:
@Testpublic void testConstructor() { // 建立容器物件,載入Spring設定檔 // ClassPathXmlApplicationContext會從類路徑下尋找設定檔 ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); ISomeService service = (ISomeService) ac.getBean("myService"); service.doSomeThing();}
此時程式會報以下的錯誤:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService' defined in class path resource [applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.ietree.spring.basic.ioc.SomeServiceImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.ietree.spring.basic.ioc.SomeServiceImpl.<init>() at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1155) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) at com.ietree.spring.basic.test.MyTest.testConstrutor(MyTest.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.ietree.spring.basic.ioc.SomeServiceImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.ietree.spring.basic.ioc.SomeServiceImpl.<init>() at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:85) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1147) ... 36 moreCaused by: java.lang.NoSuchMethodException: com.ietree.spring.basic.ioc.SomeServiceImpl.<init>() at java.lang.Class.getConstructor0(Unknown Source) at java.lang.Class.getDeclaredConstructor(Unknown Source) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:80) ... 37 more
解析:這裡的錯誤判的很明顯,沒有發現預設的構造器。
修改:為該類加上無參構造器:
package com.ietree.spring.basic.ioc;/** * 實作類別 * * @author Root */public class SomeServiceImpl implements ISomeService { private int a; public SomeServiceImpl() { System.out.println("執行無參構造器,建立SomeServiceImpl對象"); } public SomeServiceImpl(int a) { this.a = a; } @Override public void doSomeThing() { System.out.println("執行doSomeThing()方法..."); }}
此時,再次運行測試案例,會發現運行成功。
結論:Spring容器實際上是使用了類的反射機制,會首先調用Bean類的無參構造器建立執行個體對象。
二、動態工廠Bean
建立SomeServiceImpl類:
package com.ietree.spring.basic.ioc;/** * 實作類別 * * @author Root */public class SomeServiceImpl implements ISomeService { public SomeServiceImpl() { System.out.println("執行無參構造器,建立SomeServiceImpl對象"); } @Override public void doSomeThing() { System.out.println("執行doSomeThing()方法..."); }}
建立工廠類ServiceFactory:
package com.ietree.spring.basic.ioc;/** * 工廠類 * * @author Root */public class ServiceFactory { public ISomeService getSomeService() { return new SomeServiceImpl(); }}
使用動態工廠方式擷取Bean對象,配置如下:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 註冊動態工廠 --> <bean id="factory" class="com.ietree.spring.basic.ioc.ServiceFactory"/> <!-- 註冊Service:動態工廠Bean --> <bean id="myService" factory-bean="factory" factory-method="getSomeService"/> </beans>
在這裡並沒有註冊SomeServiceImpl類,而是通過ServiceFactory工廠的getSomeService方法擷取的。
測試:
@Testpublic void testFactory1() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); ISomeService service = (ISomeService) ac.getBean("myService"); service.doSomeThing();}
運行成功。
三、靜態工廠Bean
靜態工廠和動態工廠不同的是,靜態工廠中使用的是靜態方法建立對象,如:
package com.ietree.spring.basic.ioc;/** * 工廠類 * * @author Root */public class ServiceFactory { // 使用靜態方法建立對象 public static ISomeService getSomeService() { return new SomeServiceImpl(); }}
對應的設定檔修改如下:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 註冊Service:靜態工廠Bean --> <bean id="myService" class="com.ietree.spring.basic.ioc.ServiceFactory" factory-method="getSomeService"/> </beans>
測試:
@Testpublic void testFactory1() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); ISomeService service = (ISomeService) ac.getBean("myService"); service.doSomeThing();}
成功建立SomeServiceImpl對象。
四、容器中的Bean的範圍
Bean的範圍(scope)分為四種,分別是singleton、prototype、request、session。
scope:
singleton(預設):單例模式,其對象的建立時機是在Spring容器初始化時建立,是預設值
prototype:原型模式,其對象的建立時機不是在Spring容器初始化時建立,而是在代碼中真正訪問時才建立,每次使用getBean方法擷取的同一個<bean/>的執行個體都是一個新的執行個體
request:對於每次HTTP請求,都將會產生一個不同的Bean執行個體
session:對於每個不同的HTTP session,都將會產生一個不同的Bean執行個體
驗證:
首先配置範圍為singleton:
<bean id="myService" class="com.ietree.spring.basic.ioc.SomeServiceImpl" scope="singleton"/>
測試:
@Testpublic void test05() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); ISomeService service1 = (ISomeService) ac.getBean("myService"); ISomeService service2 = (ISomeService) ac.getBean("myService"); System.out.println("service1 = service2嗎?" + (service1 == service2));}
程式輸出:
調用無參構造器service1 = service2嗎?true
結論:當範圍為singleton單例模式時,只會建立一個對象執行個體,並且對象是在Spring容器初始化時建立。
同樣,當配置為prototype原型模式時:
<bean id="myService" class="com.ietree.spring.basic.ioc.SomeServiceImpl" scope="prototype"/>
程式輸出:
調用無參構造器調用無參構造器service1 = service2嗎?false
結論:構造器被調用了兩次,說明建立的service1和service2不是同一個對象,並且對象是在被使用到時才建立的。
五、Bean後處理器
六、定製Bean的生命週期
七、<bean/>標籤的id屬性與name屬性