-
beans.xml中配置
<!-- 三种实例化bean的方式 --> <!-- 1.使用类构造器实例化 --> <bean id="personService" class="com.liuyong666.service.impl.PersonServiceBean"></bean> <!-- 2.使用静态工厂方法实例化 --> <bean id="personService2" class="com.liuyong666.service.impl.PersonServiceBeanFactory" factory-method="createPersonServiceBean"></bean> <!-- 3.使用实例工厂方法实例化 --> <bean id="personServiceFactory" class="com.liuyong666.service.impl.PersonServiceBeanFactory"></bean> <bean id="personService3" factory-bean="personServiceFactory" factory-method="createPersonServiceBean2"></bean>
-
PersonServiceBeanFactory类
package com.liuyong666.service.impl; public class PersonServiceBeanFactory { public static PersonServiceBean createPersonServiceBean(){ return new PersonServiceBean(); } public PersonServiceBean createPersonServiceBean2(){ return new PersonServiceBean(); } }
-
测试类
public class TestSpring {
/**
* 使用spring框架获取bean
*/
@Test
public void getBeanBySpring(){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});
PersonService bean = (PersonService) context.getBean("personService");
bean.save();
}
/**
* 使用静态工厂方法获取bean
*/
@Test
public void getBeanByStaticFactory(){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});
PersonService bean = (PersonService) context.getBean("personService2");
bean.save();
}
/**
* 使用实例工厂方法获取bean
*/
@Test
public void getBeanByInstantceFactory(){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});
PersonService bean = (PersonService) context.getBean("personService3");
bean.save();
}
}