spring bean 例項工廠例項化
阿新 • • 發佈:2018-11-08
spring bean 例項工廠例項化
在工廠類中建立一個例項方法來例項化物件。在配置bean時需要使用factory-bean屬性指定配置的例項工廠,同時還需要使用factory-method屬性指定例項工廠中的例項方法
1.建立工廠類BeanInstanceFactory
package instance;
public class BeanInstanceFactory {
public BeanClass createBeanClassInstance() {
return new BeanClass("呼叫例項工廠方法例項化bean");
}
}
2.編輯配置檔案
<?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="constructorInstance" class="instance.BeanClass"> <!-- collaborators and configuration for this bean go here --> </bean> <!-- 靜態工廠例項化bean --> <bean id="staticFacoryInstance" class="instance.BeanStaticFactory" factory-method="createInstance"> </bean> <!-- 配置工廠 --> <bean id="myFactory" class="instance.BeanInstanceFactory"> </bean> <!-- 例項工廠例項化bean --> <bean id="instanceFacoryInstance" factory-bean="myFactory" factory-method="createBeanClassInstance"> </bean> </beans>
3.新增測試程式碼
package test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import instance.BeanClass; public class TestInstance { public static void main(String[] args) { ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml"); BeanClass b1 = (BeanClass)appCon.getBean("constructorInstance"); System.out.println(b1+b1.message); //測試靜態工廠例項化bean BeanClass b2 =(BeanClass)appCon.getBean("staticFacoryInstance"); System.out.println(b2+b2.message); //測試例項廣場例項化bean BeanClass b3 =(BeanClass)appCon.getBean("instanceFacoryInstance"); System.out.println(b3+b3.message); } }