现在的位置: 首页 > 综合 > 正文

Spring之FactoryBean

2014年01月05日 ⁄ 综合 ⁄ 共 2484字 ⁄ 字号 评论关闭

由Spring的bean容器管理的并且实现了FactoryBean接口的类实例本身也是一个bean factory,通过spring的bean容器的getBean()方法获得bean实例时,实际上获得的是这个bean factory生产出来的实例对像,而非这个bean factory本身,但在getBean()指定的beanName前加上"&"符号就获得了这个bean factory本身的实例.在spring框架中就有很多地方使用了FactoryBean,例如
org.springframework.aop.framework.ProxyFactoryBean等.下面介绍几个spring框架已提供的常用 的FactoryBean.

MethodInvokingFactoryBean :简言之为没有实现FactoryBean的应用bean提供工厂功能,即通过指定目标类或实现及相应的方法名称(如果需要方法参数还要提供相应参数),就可以获得该方法的返回值.

具体来说,MethodInvokingFactoryBean把静态或实例方法调用的返回值作为自己的返回对象.尽管推荐使用容器内置的工厂方法 来达到相同的目的,但当你要调用的工厂方法没有返回值时,使用MethodInvokingFactoryBean或许会给你带来帮助,因为内置的工厂方 法作为bean容器的一部分,是为了对外提供实例,故而不支持没有返回值的场景.

MethodInvokingFactoryBean依赖于InitializingBean.afterPropertiesSet(),即当 BeanFactory完成所有的属性设置后,会调用InitializingBean的afterPropertiesSet()方法来实现一些个性化 的初始化过程.MethodInvokingFactoryBean实现了InitializingBean,并且在其 afterPropertiesSet()方法中对于singleton
bean执行方法调用,如下:

  1. public void afterPropertiesSet() throws Exception {  
  2.     prepare();  
  3.     if (this.singleton) {  
  4.         this.initialized = true;  
  5.         this.singletonObject = doInvoke();  
  6.     }  
  7. }  

MethodInvokingFactoryBean支持静态方法调用和实例方法调用,其唯一不同在于前者需要提供targetClass,而后者需要提供targetObject,分别配置如下:

  • 静态调用方式一:
  1. <bean id="myObject" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">  
  2.           <property name="staticMethod">  
  3.                   <value>com.enjiex.MyFactory.getInstance</value>  
  4.           </property>  
  5.   </bean>  
  • 静态调用方式二:
  1. <bean id="myObject" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">  
  2.         <property name="targetClass">  
  3.                 <value>com.enjiex.MyFactory</value>  
  4.         </property>  
  5.         <property name="targetMethod">  
  6.                 <value>getInstance</value>  
  7.         </property>  
  8. </bean>  
  • 实例调用方式:
  1. <bean id="myObject" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">  
  2.         <property name="targetObject">  
  3.                 <value>myFactory</value>  
  4.         </property>  
  5.         <property name="targetMethod">  
  6.                 <value>getInstance</value>  
  7.         </property>  
  8.         <!--  
  9.                 如果有必要可指定arguments属性用于设置方法参数  
  10.         -->  
  11. </bean>  

不管哪种方式,当需要myObject bean时,实际返回的是targetObject.getInstance()或者targetClass.getInstance()

MethodInvokingFactoryBean相当于对FactoryBean提供了个性化的实现,当应用需要使用FactoryBean的 时候,即不用实现FactoryBean并使用指定的getObject方法,也不用继承和框架相关的类,降低了业务应用与框架的耦合.



转载地址:http://enjiex.blogbus.com/logs/199504575.html?

抱歉!评论已关闭.