BeanFactory:是Spring的一个工厂它能够得到Spring工厂给创建的Bean,能通过getBean()方法获得。
FactoryBean:是一个特殊的Bean,Spring管理它的时候会对实现这个接口的类前面加一个(&)字符。而它的名字则是表示getObject中得到的Bean。主要的作用是别的Bean属性或者依赖太多的情况下,都可以通过FactoryBean生成不太容易的Bean,然后对外提供简单化的Bean
public class TempDaoFactoryBean {
public void test(){
System.out.println("bean");
}
}
/**
* 如果你的类实现了FactoryBean
* 那么Spring容器中会存在两个对象
* 一个是getObject返回的对象
* 一个是当前对象
*
* getObject得到的名字是当前类指定的名字,也就是Spring中daoFactoryBean对应的对象
*
* 当前对象是当前类的名字是“&”+当前类的名字
*
* */
@Component("daoFactoryBean")
public class DaoFactoryBean implements FactoryBean {
public void testBean(){
System.out.println("testBean");
}
public Object getObject() throws Exception {
return new TempDaoFactoryBean();
}
public Class<?> getObjectType() {
return null;
}
public boolean isSingleton() {
return false;
}
}
依赖关系比较复杂的时候可以使用FactoryBean,例如SqlSessionFactoryBean,就是使用的Factory这种模式,对外进行简化它的庞大资源配置的。
简单一个例子来模拟庞大的复杂关系
package com.FactoryBeanPackage;
import org.springframework.beans.factory.FactoryBean;
public class DaoFactoryBean implements FactoryBean {
private String msg;
public void setMsg(String msg) {
this.msg = msg;
}
public void testBean(){
System.out.println("testBean");
}
public Object getObject() throws Exception {
TempDaoFactoryBean temp=new TempDaoFactoryBean();
String msgArrags[]=msg.split(",");
temp.setMsg(msgArrags[0]);
temp.setMsg2(msgArrags[1]);
temp.setMsg3(msgArrags[2]);
return temp;
}
public Class<?> getObjectType() {
return null;
}
public boolean isSingleton() {
return false;
}
}
package com.FactoryBeanPackage;
public class TempDaoFactoryBean {
private String msg;
private String msg2;
private String msg3;
public void setMsg(String msg) {
this.msg = msg;
}
public void setMsg2(String msg2) {
this.msg2 = msg2;
}
public void setMsg3(String msg3) {
this.msg3 = msg3;
}
public String getMsg() {
return msg;
}
public String getMsg2() {
return msg2;
}
public String getMsg3() {
return msg3;
}
public void test(){
System.out.println("bean");
}
}
package com.FactoryBeanPackage;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext act=
new AnnotationConfigApplicationContext(SpringDaoFactoryConfig.class);
TempDaoFactoryBean daoFactoryBean= (TempDaoFactoryBean) act.getBean("daoFactor");
System.out.println(daoFactoryBean.getMsg());
}
}
package com.FactoryBeanPackage;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
@ComponentScan(value = "com.FactoryBeanPackage")
@ImportResource("classpath:spring.xml")
public class SpringDaoFactoryConfig {
}