文章40 | 阅读 19285 | 点赞0
Spring提供了三种实例化Bean的方式。
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
不难看出,我们以前使用的就是该方式。上面的配置默认使用的是PersonServiceBean类的默认构造函数来实例化PersonServiceBean对象的。
public class PersonServiceBeanFactory {
public static PersonServiceBean createPersonServiceBean() {
return new PersonServiceBean();
}
}
然后修改Spring的配置文件为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
<bean id="personService2" class=" cn.itcast.service.impl.PersonServiceBeanFactory" factory-method="createPersonServiceBean" />
</beans>
最后,将SpringTest类的改为:
public class SpringTest {
@Test
public void test() {
// ApplicationContext是接口
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 实例化Spring容器
PersonService personService = (PersonService) ctx.getBean("personService2"); // 从Spring容器取得bean
personService.save();
}
}
测试test()方法,Eclipse控制台打印如下:
public class PersonServiceBeanFactory {
public static PersonServiceBean createPersonServiceBean() {
return new PersonServiceBean();
}
public PersonServiceBean createPersonServiceBean2() {
return new PersonServiceBean();
}
}
紧接着修改Spring的配置文件为:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean"></bean>
<bean id="personService2" class=" cn.itcast.service.impl.PersonServiceBeanFactory" factory-method="createPersonServiceBean" />
<bean id="personServiceBeanFactory" class="cn.itcast.service.impl.PersonServiceBeanFactory"></bean>
<bean id="personService3" factory-bean="personServiceBeanFactory" factory-method="createPersonServiceBean2"></bean>
</beans>
最后,将SpringTest类的改为:
public class SpringTest {
@Test
public void test() {
// ApplicationContext是接口
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); // 实例化Spring容器
PersonService personService = (PersonService) ctx.getBean("personService3"); // 从Spring容器取得bean
personService.save();
}
}
测试test()方法,Eclipse控制台打印如下:
Spring提供了三种实例化Bean的方式,那么到底该使用哪种方式较稳妥呢?应根据实际情况决定,但可这样说,90%的可能都是采用第一种方式,即使用类构造器实例化bean。源码可点击**Spring的三种实例化Bean的方式**进行下载。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://liayun.blog.csdn.net/article/details/52832793
内容来源于网络,如有侵权,请联系作者删除!