本书可作为王富强所著<<Spring揭秘>>一书的读书笔记
第四章 BeanFactory的xml之旅
public class Foo { private BarInterface barInstance; public Foo() { // 我们应该避免这样做 // instance = new BarInterfaceImpl(); } // ... }
public class Foo { private BarInterface barInterface; public Foo() { // barInterface = BarInterfaceFactory.getInstance(); // 或者 // barInterface = new BarInterfaceFactory().getInstance(); } ... }
public class StaticBarInterfaceFactory { public static BarInterface getInstance() { return new BarInterfaceImpl(); } }
<bean id="foo" class="...Foo"> <property name="barInterface"> <ref bean="bar"/> </property> </bean> <bean id="bar" class="...StaticBarInterfaceFactory" factory-method="getInstance"/>
public class StaticBarInterfaceFactory { public static BarInterface getInstance(Foobar foobar) { return new BarInterfaceImpl(foobar); } }xml如下:
<bean id="foo" class="...Foo"> <property name="barInterface"> <ref bean="bar"/> </property> </bean> <bean id="bar" class="...StaticBarInterfaceFactory" factory-method="getInstance"> <constructor-arg> <ref bean="foobar"/> </constructor-arg> </bean> <bean id="foobar" class="...FooBar"/>
public class NonStaticBarInterfaceFactory { public BarInterface getInstance() { return new BarInterfaceImpl(); } ... }
<bean id="foo" class="...Foo"> <property name="barInterface"> <ref bean="bar"/> </property> </bean> <bean id="barFactory" class="...NonStaticBarInterfaceFactory"/> <bean id="bar" factory-bean="barFactory" factory-method="getInstance"/>
public interface FactoryBean { Object getObject() throws Exception; Class getObjectType(); //如果不能确定返回的类型,getObjectType就返回null boolean isSingleton(); }完全能看懂,没有压力呀。
import org.joda.time.DateTime; import org.springframework.beans.factory.FactoryBean; public class NextDayDateFactoryBean implements FactoryBean { public Object getObject() throws Exception { return new DateTime().plusDays(1); } public Class getObjectType() { return DateTime.class; } public boolean isSingleton() { return false; } }要使用NextDayDateFactoryBean,只需要如下这样将其注册到容器即可:
<bean id="nextDayDateDisplayer" class="...NextDayDateDisplayer"> <property name="dateOfNextDay"> <ref bean="nextDayDate"/> </property> </bean> <bean id="nextDayDate" class="...NextDayDateFactoryBean"> </bean>从xml配置上似乎和以前没有什么差别,但是nextDayDateDisplayer里的属性dateOfNextDay并不是NextDayDateFactoryBean而是NextDayDateFactoryBean中getObject方法返回的对象。
public class NextDayDateDisplayer { private DateTime dateOfNextDay; // 相应的setter方法 // ... }
Object nextDayDate = container.getBean("nextDayDate"); assertTrue(nextDayDate instanceof DateTime); Object factoryBean = container.getBean("&nextDayDate"); assertTrue(factoryBean instanceof FactoryBean); assertTrue(factoryBean instanceof NextDayDateFactoryBean); Object factoryValue = ((FactoryBean)factoryBean).getObject(); assertTrue(factoryValue instanceof DateTime); assertNotSame(nextDayDate, factoryValue); ssertEquals( ((DateTime)nextDayDate).getDayOfYear(), ((DateTime)factoryValue).getDayOfYear() );
感谢glt