Spring框架实例化Bean有3种方式,即构造方法实例化、静态工厂实例化、实例工厂实例化(其中最常用的是构造方法实例化)
package instance;
public class BeanClass {
public String message;
public BeanClass() {
message = "构造方法实例化Bean";
}
public BeanClass(String s) {
message = s;
}
}
package instance;
public class BeanStaticFactory {
private static BeanClass beanInstance = new BeanClass("调用静态工厂方法实例化Bean");
public static BeanClass createInstance(){
return beanInstance;
}
}
package instance;
public class BeanInstanceFactory {
public BeanClass createBeanClassInstance(){
return new BeanClass("调用实例工厂方法实例化Bean");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!-- - Application context definition for JPetStore's business layer. - Containsbean
references to the transaction manager and to the DAOs in - dataAccessContext-local/jta.xml(see
web.xml's "contextConfigLocation"). -->
<beans
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans">
<bean id="constructorInstance" class="instance.BeanClass" />
<!-- 构造方法实例化 -->
<!-- 静态工厂方法实例化Bean,createInstance为静态工厂类BeanStaticFactory中的静态方法 -->
<bean id="staticFactoryInstance" class="instance.BeanStaticFactory"
factory-method="createInstance" />
<!-- 配置工厂 -->
<bean id="myFactory" class="instance.BeanInstanceFactory" />
<!-- 使用factory-bean属性指定配置工厂,使用factory-method属性指定使用工厂中的哪个方法实例化Bean -->
<bean id="instanceFactoryInstance" factory-bean="myFactory"
factory-method="createBeanClassInstance" />
</beans>
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) {
// TODO Auto-generated method stub
ApplicationContext xfc = new ClassPathXmlApplicationContext("applicationContext.xml");
// 初始化Spring容器ApplicationContext,加载配置文件
BeanClass b1 = (BeanClass) xfc.getBean("constructorInstance");
// 测试构造方法实例化Bean
System.out.println(b1 + b1.message);
// 测试静态工厂方法实例化Bean
BeanClass b2 = (BeanClass) xfc.getBean("staticFactoryInstance");
System.out.println(b2 + b2.message);
// 测试实例工厂方法实例化Bean
BeanClass b3 = (BeanClass) xfc.getBean("instanceFactoryInstance");
System.out.println(b3 + b3.message);
}
}
instance.BeanClass@49993335构造方法实例化Bean
instance.BeanClass@20322d26调用静态工厂方法实例化Bean
instance.BeanClass@192b07fd调用实例工厂方法实例化Bean