1、使用类构造器进行实例化
<bean id="personIService" class="cn.server.impl.PersonServiceImpl" />
测试代码:
@Test public void test() { ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml"); PersonIService personIService=(PersonIService)ac.getBean("personIService"); personIService.helloSpring(); }
2、使用静态工厂实例化
public class BeanFactory { public static PersonServiceImpl createPersonServiceImpl(){ return new PersonServiceImpl(); } }
<bean id="personIService2" class="cn.BeanFactory" factory-method="createPersonServiceImpl" />
测试代码:
@Test public void test3() { ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml"); PersonIService personIService=(PersonIService)ac.getBean("personIService2"); personIService.helloSpring(); }
3、使用实例化工厂实例化
public class BeanFactory { public PersonServiceImpl createPersonServiceImpl2(){ return new PersonServiceImpl(); } }
<bean id="beanFactory" class="cn.BeanFactory"/> <bean id="personIService3" factory-bean="beanFactory" factory-method="createPersonServiceImpl2" />
测试代码:
@Test public void test4() { ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml"); PersonIService personIService=(PersonIService)ac.getBean("personIService3"); personIService.helloSpring(); }