BeanFactory
BeanFactory是spring中IOC容器的基礎形式,給具體的IOC容器的實現提供了規範。正如ApplicationContext就是他派生而來,以及常用的具體實現ClassPathXmlApplicationContext等,作爲框架中生產和管理bean的容器。
職責:實例化,定位,配置應用程序中的對象以及建立對象間的依賴。
FactoryBean
通常情況下,spring通過<bean>標籤中的class與property等實例化bean,某些情況下,使用這種傳統配置實例化bean很繁瑣,配置方式靈活度有限,此時使用編碼的方式可能會得到一個簡單方案。spring爲此提供了一個FactoryBean的工廠類接口,通過實現該接口定製化bean的邏輯。
FactoryBean以bean結尾,說明他也是一個bean,但是有別於普通的bean:他是實現了FactoryBean<T>接口的bean,通過id獲取FactoryBean.getObject()返回的對象。而不是FactoryBean<T>本身,若想獲取他本身需要在id前加一個&。
下面代碼加深理解:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="student" class="com.spring.bean.Student">
<property name="name" value="zhangsan" />
</bean>
<bean id="school" class="com.spring.bean.School">
</bean>
<bean id="factoryBeanPojo" class="com.spring.bean.FactoryBeanPojo">
<property name="type" value="student" />
</bean>
</beans>
public class FactoryBeanPojo implements FactoryBean{
private String type;
@Override
public Object getObject() throws Exception {
if("student".equals(type)){
return new Student();
}else{
return new School();
}
}
@Override
public Class getObjectType() {
return School.class;
}
@Override
public boolean isSingleton() {
return true;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public class FactoryBeanTest {
public static void main(String[] args){
String url = "com/spring/config/BeanConfig.xml";
ClassPathXmlApplicationContext cpxa = new ClassPathXmlApplicationContext(url);
Object school= cpxa.getBean("factoryBeanPojo");
FactoryBeanPojo factoryBeanPojo= (FactoryBeanPojo) cpxa.getBean("&factoryBeanPojo");
System.out.println(school.getClass().getName());
System.out.println(factoryBeanPojo.getClass().getName());
}
}
輸出:
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@35b793ee: defining beans [student,school,factoryBeanPojo]; root of factory hierarchy
com.spring.bean.Student
com.spring.bean.FactoryBeanPojo
以上說明,factoryBean的靈活性以及他的特性getBean('id'),是獲取getObject的實例;getBean('&id'),獲取的是factoryBean的實例