1. Bean实例化的方法
a. 普通方法
b. 静态工厂方法
c. 工厂方法
a. 普通方法
public class PersonServiceBean implements PersonService {
public void save(){
System.out.println("我是save()方法");
}
}<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean> @Test
public void instanceSpring(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService)ctx.getBean("personService");
personService.save();
}b. 静态工厂方法
public class PersonServiceBeanFactory {
public static PersonServiceBean createPersonServiceBean(){
return new PersonServiceBean();
}
}<bean id="personService2" class="cn.itcast.service.impl.PersonServiceBeanFactory"
factory-method="createPersonServiceBean"/> @Test
public void instanceSpring(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService)ctx.getBean("personService2");
personService.save();
}c. 工厂方法
public class PersonServiceBeanFactory {
public PersonServiceBean createPersonServiceBean2(){
return new PersonServiceBean();
}
}<bean id="personServiceFactory" class="cn.itcast.service.impl.PersonServiceBeanFactory"/>
<bean id="personService3" factory-bean="personServiceFactory" factory-method="createPersonServiceBean2"/> @Test
public void instanceSpring(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService)ctx.getBean("personService3");
personService.save();
}
本文介绍了Spring框架中Bean的三种实例化方法:普通方法、静态工厂方法和工厂方法,并提供了具体的实现示例。
5万+

被折叠的 条评论
为什么被折叠?



