Spring bean实例化方式
无参构造函数实例化(最常见的方式)
类文件
public class ExampleBean{
public void print(String val) {
System.out.println("com.woniu..spring.test.ExampleBean:print ->" + val);
}
}
bean
<bean id="exampleBean" class="com.woniu.spring.test.ExampleBean"/>
测试类
public void SpringBeansTest() {
ApplicationContext beans = new ClassPathXmlApplicationContext("spring_context_test.xml");
ExampleBean exampleBean= (ExampleBean) beans.getBean("exampleBean");
exampleBean.print("无参数构造");
}
静态工厂方法实例化
静态工厂类
public class ExampleBeanStaticFactory {
private static ExampleBean exampleBean = new ExampleBean();
private ExampleBeanStaticFactory () {}
public static ExampleBean createExampleBean() {
return exampleBean;
}
}
bean
<bean id="createExampleBean" class="com.woniu.spring.test.ExampleBeanStaticFactory" factory-method="createExampleBean"/>
测试方法
public void SpringBeansTest() {
ApplicationContext beans = new ClassPathXmlApplicationContext("spring_context_test.xml");
ExampleBean createExampleBean = (ExampleBean) beans.getBean("createExampleBean");
createExampleBean.print("静态工厂类实例化");
}
实例工厂方法实例化
实例工厂类
一个工厂类可以包含多个工厂方法
public class ExampleBeanStaticFactory {
private ExampleBean exampleBean1 = new ExampleBean();
private ExampleBean exampleBean2 = new ExampleBean();
public static ExampleBean createExampleBean1() {
return exampleBean1;
}
public static ExampleBean createExampleBean1() {
return exampleBean2;
}
}
bean
将该class属性保留为空,并在factory-bean属性中指定当前容器中bean的名称,该容器包含要调用创建对象的实例方法
<bean id="exampleBeanStaticFactory " class="com.woniu.spring.test.ExampleBeanStaticFactory ">
</bean>
<bean id="createExampleBean1" factory-bean="exampleBeanStaticFactory " factory-method="createExampleBean1"/>
<bean id="createExampleBean2" factory-bean="exampleBeanStaticFactory " factory-method="createExampleBean1"/>
测试类
public void SpringBeansTest() {
ApplicationContext beans = new ClassPathXmlApplicationContext("spring_context_test.xml");
ExampleBean createExampleBean1 = (ExampleBean) beans.getBean("createExampleBean1");
ExampleBean createExampleBean2 = (ExampleBean) beans.getBean("createExampleBean2");
createExampleBean1.print("实例工厂方法一");
createExampleBean2.print("实例工厂方法二");
}