Spring实例化Bean的三种方式及Bean的类型

时间:2022-12-18 19:05:26

1.使用类构造器实例化  [默认的类构造器]

<bean id=“orderService" class="cn.itcast.OrderServiceBean"/>


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

<bean id="personService" class="cn.itcast.service.OrderFactory" factory-method="createOrder"/>

public class OrderFactory {
// 注意这里的这个方法是 static 的!
public static OrderServiceBean createOrder(){
return new OrderServiceBean();
}
}

 

3.使用实例工厂方法实例化:

<bean id="personServiceFactory" class="cn.itcast.service.OrderFactory"/>
<bean id="personService" factory-bean="personServiceFactory" factory-method="createOrder"/>

public class OrderFactory {
public OrderServiceBean createOrder(){
return new OrderServiceBean();
}
}

在BAMS中,工作流引擎activiti的各个组件就是使用此方式实例化的。 

<bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean">
<property name="processEngineConfiguration" ref="processEngineConfiguration"/>
</bean>

<bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService"/>
<bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService"/>
<bean id="formService" factory-bean="processEngine" factory-method="getFormService"/>
<bean id="identityService" factory-bean="processEngine" factory-method="getIdentityService"/>
<bean id="taskService" factory-bean="processEngine" factory-method="getTaskService"/>
<bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService"/>
<bean id="managementService" factory-bean="processEngine" factory-method="getManagementService"/>

使用工厂实例化的Bean跟普通Bean不同,其返回的对象不是指定类的一个实例,其返回的是该FactoryBean的getObject方法所返回的对象。以下为ProcessEngineFactoryBean源码。

public class ProcessEngineFactoryBean implements FactoryBean<ProcessEngine> ..{
...
protected ProcessEngineImpl processEngine;

public ProcessEngine getObject() throws Exception {
initializeExpressionManager();
initializeTransactionExternallyManaged();

if (processEngineConfiguration.getBeans()==null) {
processEngineConfiguration.setBeans(
new SpringBeanFactoryProxyMap(applicationContext));
}

processEngine
= (ProcessEngineImpl) processEngineConfiguration.buildProcessEngine();

return processEngine;
}

...
}

ProcessEngineFactoryBean最终返回的是processEngine对象,repositoryService、runtimeService、formService等等组件都是通过processEngine里的getXX方法获得的。

 

总结:Spring中有三种实例化Bean的方式,类构造器实例化、静态工厂方法实例化及实例工厂方法实例化。两种Bean类型,一种是普通Bean,另一种是工厂Bean,即FactoryBean,这两种Bean都被容器管理,但工厂Bean跟普通Bean不同,其返回的对象不是指定类的一个实例,其返回的是该FactoryBean的getObject方法所返回的对象。在Spring框架内部,有很多地方有FactoryBean的实现类,它们在很多应用如(Spring的AOP、ORM、事务管理)及与其它第三框架(ehCache)集成时都有体现。

原文出自:http://www.pinhuba.com/spring/101034.htm