spring--工厂方法与FactoryBean

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qfzhangwei/article/details/79684411

spring 引入第三方类时常用方法

1 静态工厂

public class Foo{
   private BarInterface barInterface;
   public Foo(){
   }
}

<bean id = "foo" class="...Foo">
   <property name = "barInterface">
      <ref bean="bar"/>
   </property>
</bean>
xml 配置静态工厂方法
<bean id = "bar" class = "...StaticBarInterfaceFactory" factory-method="getInstance">

静态工厂定义
public class StaticBarInterfaceFactory{
   public static BarInterface getInstance(){
      return new BarInterfaceImpl();
   }
}

2 动态工厂

动态工厂定义class
public class NonStaticBarInterfaceFactory{
   public BarInterface getInstance(){
       return new BarInterfaceImpl();
   }
}
xml配置
<bean id = "foo" class ="...Foo">
    <property name="barInterface">
       <ref bean="bar"/>
    </property>
</bean>
//动态工厂bean
<bean id="barFactory" class="...NonStaticBarInterfaceFactory"/>
//工厂方法
<bean id="bar" factory-bean="barFactory" factory-method="getInstance"/>

3 FactoryBean--不再需要指定factory-method,实用接口默认的getObject方法获取实例

public interface FactoryBean{
   Object getObject() throws Exception;
   Class getObjectType();
   boolean isSingleton();
}

public class NextDateFactoryBean implements FactoryBean(){
   public Object getObject() throws Exception{
        return new DateTime().plusDays(1);
   }
   public Class getObjectType(){
      return DateTime.class;
   }
   public boolean isSingleton(){
       return false;
   }
}

xml配置
<bean id = "nextDayDateDisplayer" class="...NextDayDateDisplayer">
 
   <property name="dateOfNextDay">
       <ref bean ="nextDayDate">
   </property>

</bean>

<bean id = "nextDayDate" class="...NextDayDateFactoryBean"/>//获取FactoryBean产生的bean

猜你喜欢

转载自blog.csdn.net/qfzhangwei/article/details/79684411
今日推荐