欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

三种实例化Spring中Bean对象的方式

程序员文章站 2022-03-03 12:28:36
...

1、使用类构造器实例化。

<!-- 使用类构造器实例化bean -->

<bean id="stockService" class="cn.itcast.service.impl.StockServiceImpl"></bean>

2、使用静态工厂方法实例化bean

<!-- 使用静态工厂方法实例化bean -->

<bean id="personServiceFactory" class="cn.itcast.service.impl.PersonServiceBeanFactory" factory-method="createPersonServiceBeanFactory"></bean>

3、使用实例化工厂方法实例化bean

<!-- 使用实例化工厂方法实例化bean-->

<!--首先实例化工厂对象 -->

<bean id="personServiceFactory2" class="cn.itcast.service.impl.PersonServiceBeanFactory"></bean>

<!-- 在实例化Bean对象 -->

<bean id="personServiceFactory3" factory-bean="personServiceFactory2" factory-method="createPersonServiceBeanFactory2"></bean>

 

package cn.itcast.service.impl;

public class PersonServiceBeanFactory {
public static PersonServiceBean createPersonServiceBeanFactory() {
return new PersonServiceBean();
}
public PersonServiceBean createPersonServiceBeanFactory2() {
return new PersonServiceBean();
}
}

测试Case
@Test public void instanceSpring3() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService)ctx.getBean("personServiceFactory3");
personService.save();
}