这里的工厂方法指的是创建指定bean的方法。工厂方法又分为静态工厂方法和实例工厂方法。
调用静态工厂方法创建Bean是将对象创建的过程封装到静态方法中,不需要创建工厂实例就可以返回工厂创建的对象,就叫做静态工厂,当客户端需要对象时,只需要简单的调用静态方法,而不需要关心创建对象的细节。要声明通过静态方法创建的Bean,需要在Bean的class属性指定拥有该工厂的方法的类,同时在factory-method属性里指定工厂方法的名称,最后使用
首先创建一个提供静态工厂方法的类:
1 public class StaticCarFactory { 2 private static Mapcars = new HashMap (); 3 static { 4 cars.put("audi", new Car("audi", 300000)); 5 cars.put("ford", new Car("audi", 400000)); 6 } 7 //静态工厂方法,根据名字获取car对象 8 public static Car getCar(String name) { 9 return cars.get(name); 10 } 11 }
spring配置文件
1 2 78 9
编写Main测试类
1 public class Main { 2 public static void main(String[] args) { 3 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml"); 4 5 Car car1 = (Car) ctx.getBean("car1"); 6 7 System.out.println(car1); 8 } 9 }
输出结果:我们可以看到通过静态工厂成功创建了一个对象。
使用实例工厂方法配置bean首先需要创建一个实例工厂的bean,通过调用实例工厂bean的非静态方法创建目标的bean对象,同时在factory-bean属性里指定工厂bean的id,最后使用
首先创建一个实例工厂的bean:
1 public class InstanceCarFactory { 2 private Mapcars = null; 3 4 public InstanceCarFactory() { 5 cars = new HashMap (); 6 cars.put("audi", new Car("audi", 300000)); 7 cars.put("ford", new Car("ford", 400000)); 8 } 9 10 public Car getCar(String name){ 11 return cars.get(name); 12 } 13 14 }
配置Spring配置文件
1 2 78 9 10 11
修改Main测试类:
1 public class Main { 2 public static void main(String[] args) { 3 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml"); 4 5 Car car2 = (Car) ctx.getBean("car2"); 6 7 System.out.println(car2); 8 } 9 }
输出结果:
配置bean有三种方式:通过全类名(class反射)、通过工厂方法(静态工厂&实例工厂)、通过FactoryBean。前面我们已经一起学习过全类名方式和工厂方法方式,下面通过这篇文章来学习一下FactroyBean.
FactoryBean是Spring给我们提供的一个接口,我们来看一下这个接口的源码:
1 public interface FactoryBean{ 2 @Nullable 3 T getObject() throws Exception; 4 5 @Nullable 6 Class> getObjectType(); 7 8 default boolean isSingleton() { 9 return true; 10 } 11 }
这个接口中为我们提供了三个方法:
getObject():返回bean本身
getObjectType():返回FactoryBean创建Bean的类型。
isSingleton():返回bean是否是单例的
我们有全类名配置,也有工厂方法配置,为什么我们还要用这种FactoryBean来配置Bean呢?因为我们在配置一个bean的时候需要用到另一个bean的时候,使用FactoryBean在合适不过了 下面来具体操作一下: 首先我们创建一个Car的FactoryBean去实现FactoryBean接口:
1 public class CarFactoryBean implements FactoryBean { 2 private String brand; 3 4 public void setBrand(String brand) { 5 this.brand = brand; 6 } 7 8 @Nullable 9 public Object getObject() throws Exception { 10 return new Car("BMW", 5000000); 11 } 12 13 @Nullable 14 public Class> getObjectType() { 15 return Car.class; 16 } 17 18 public boolean isSingleton() { 19 return true; 20 } 21 }
Spring配置文件:
1 2 3 45 6
编写Main测试类:
1 public class Main { 2 public static void main(String[] args) { 3 ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-factorybean.xml"); 4 5 Car car1 = (Car) ctx.getBean("car1"); 6 7 System.out.println(car1); 8 } 9 }
输出结果:
通过Factorybean来配置bean的实例,通过class来指向factorybean的全类名,property指的factory的属性,我们在配置bean的时候经常需要用的ioc容器里的其他bean,在factorybean中处理你传入的其他bean以达到目的。但实际返回的的是,getObject方法返回的实例。
这里的工厂方法指的是创建指定bean的方法。工厂方法又分为静态工厂方法和实例工厂方法。
调用静态工厂方法创建Bean是将对象创建的过程封装到静态方法中,不需要创建工厂实例就可以返回工厂创建的对象,就叫做静态工厂,当客户端需要对象时,只需要简单的调用静态方法,而不需要关心创建对象的细节。要声明通过静态方法创建的Bean,需要在Bean的class属性指定拥有该工厂的方法的类,同时在factory-method属性里指定工厂方法的名称,最后使用
首先创建一个提供静态工厂方法的类:
1 public class StaticCarFactory { 2 private static Mapcars = new HashMap (); 3 static { 4 cars.put("audi", new Car("audi", 300000)); 5 cars.put("ford", new Car("audi", 400000)); 6 } 7 //静态工厂方法,根据名字获取car对象 8 public static Car getCar(String name) { 9 return cars.get(name); 10 } 11 }
spring配置文件
1 2 78 9
编写Main测试类
1 public class Main { 2 public static void main(String[] args) { 3 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml"); 4 5 Car car1 = (Car) ctx.getBean("car1"); 6 7 System.out.println(car1); 8 } 9 }
输出结果:我们可以看到通过静态工厂成功创建了一个对象。
使用实例工厂方法配置bean首先需要创建一个实例工厂的bean,通过调用实例工厂bean的非静态方法创建目标的bean对象,同时在factory-bean属性里指定工厂bean的id,最后使用
首先创建一个实例工厂的bean:
1 public class InstanceCarFactory { 2 private Mapcars = null; 3 4 public InstanceCarFactory() { 5 cars = new HashMap (); 6 cars.put("audi", new Car("audi", 300000)); 7 cars.put("ford", new Car("ford", 400000)); 8 } 9 10 public Car getCar(String name){ 11 return cars.get(name); 12 } 13 14 }
配置Spring配置文件
1 2 78 9 10 11
修改Main测试类:
1 public class Main { 2 public static void main(String[] args) { 3 ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-factory.xml"); 4 5 Car car2 = (Car) ctx.getBean("car2"); 6 7 System.out.println(car2); 8 } 9 }
输出结果:
2018年07月23日 14:24:16 liuhmmjj 阅读数 7318更多
分类专栏: Spring
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u014082714/article/details/81166648
Spring 中有两种类型的Bean,一种是普通Bean,另一种是工厂Bean 即 FactoryBean。FactoryBean跟普通Bean不同,其返回的对象不是指定类的一个实例,而是该FactoryBean的getObject方法所返回的对象。创建出来的对象是否属于单例由isSingleton中的返回决定。
一般情况下,Spring通过反射机制利用
以Bean结尾,表示它是一个Bean,不同于普通Bean的是:它是实现了FactoryBean
package org.springframework.beans.factory;
public interface FactoryBean
T getObject() throws Exception;
Class> getObjectType();
boolean isSingleton();
}
FactoryBean 通常是用来创建比较复杂的bean,一般的bean 直接用xml配置即可,但如果一个bean的创建过程中涉及到很多其他的bean 和复杂的逻辑,用xml配置比较困难,这时可以考虑用FactoryBean。
很多开源项目在集成Spring 时都使用到FactoryBean,比如 MyBatis3 提供 mybatis-spring项目中的 org.mybatis.spring.SqlSessionFactoryBean
:
public class SqlSessionFactoryBean implements FactoryBean
private static final Log LOGGER = LogFactory.getLog(SqlSessionFactoryBean.class);
...
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
this.afterPropertiesSet();
}
return this.sqlSessionFactory;
}
...
}
下面看一下具体的源码:
AbstractBeanFactory通过getBean向IoC容器获取被管理的Bean:
AbstractBeanFactory的getBean相关方法的源码如下:
protected
final String beanName = this.transformedBeanName(name);
Object sharedInstance = this.getSingleton(beanName);
Object bean;
if (sharedInstance != null && args == null) {
if (this.logger.isDebugEnabled()) {
if (this.isSingletonCurrentlyInCreation(beanName)) {
this.logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
} else {
this.logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null);
} else {
if (this.isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
BeanFactory parentBeanFactory = this.getParentBeanFactory();
if (parentBeanFactory != null && !this.containsBeanDefinition(beanName)) {
String nameToLookup = this.originalBeanName(name);
if (args != null) {
return parentBeanFactory.getBean(nameToLookup, args);
}
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
if (!typeCheckOnly) {
this.markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);
this.checkMergedBeanDefinition(mbd, beanName, args);
String[] dependsOn = mbd.getDependsOn();
String[] var11;
if (dependsOn != null) {
var11 = dependsOn;
int var12 = dependsOn.length;
for(int var13 = 0; var13 < var12; ++var13) {
String dependsOnBean = var11[var13];
if (this.isDependent(beanName, dependsOnBean)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
}
this.registerDependentBean(dependsOnBean, beanName);
this.getBean(dependsOnBean);
}
}
if (mbd.isSingleton()) {
sharedInstance = this.getSingleton(beanName, new ObjectFactory
public Object getObject() throws BeansException {
try {
return AbstractBeanFactory.this.createBean(beanName, mbd, args);
} catch (BeansException var2) {
AbstractBeanFactory.this.destroySingleton(beanName);
throw var2;
}
}
});
bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) {
var11 = null;
Object prototypeInstance;
try {
this.beforePrototypeCreation(beanName);
prototypeInstance = this.createBean(beanName, mbd, args);
} finally {
this.afterPrototypeCreation(beanName);
}
bean = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
} else {
String scopeName = mbd.getScope();
Scope scope = (Scope)this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory
public Object getObject() throws BeansException {
AbstractBeanFactory.this.beforePrototypeCreation(beanName);
Object var1;
try {
var1 = AbstractBeanFactory.this.createBean(beanName, mbd, args);
} finally {
AbstractBeanFactory.this.afterPrototypeCreation(beanName);
}
return var1;
}
});
bean = this.getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
} catch (IllegalStateException var21) {
throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider " + "defining a scoped proxy for this bean if you intend to refer to it from a singleton", var21);
}
}
} catch (BeansException var23) {
this.cleanupAfterBeanCreationFailure(beanName);
throw var23;
}
}
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return this.getTypeConverter().convertIfNecessary(bean, requiredType);
} catch (TypeMismatchException var22) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Failed to convert bean '" + name + "' to required type [" + ClassUtils.getQualifiedName(requiredType) + "]", var22);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
} else {
return bean;
}
}
我们可以看到,无论是直接取单例的bean,还是创建单例、多例、自定义生命周期的bean,都会经过bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);这个方法,我们现在就来看看这里到底是做了什么。
protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(this.transformedBeanName(name), beanInstance.getClass());
} else if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
Object object = null;
if (mbd == null) {
object = this.getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
FactoryBean> factory = (FactoryBean)beanInstance;
if (mbd == null && this.containsBeanDefinition(beanName)) {
mbd = this.getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = mbd != null && mbd.isSynthetic();
object = this.getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
} else {
return beanInstance;
}
}
这里有必要单独说一下解引用:
Dereference(解引用):一个在C/C++中应用的比较多术语,在C++中,“*”是解引用符号,“&”是引用符号。
解引用:变量所指向的是所引用对象的本身数据,而不是对象的内存地址。
上面的代码可以看到,对于大多数bean的getBean,一般走到第二步就返回了,也就是说我们创建的Bean对象就是想要的bean,但对于FactoryBean的创建,如果是对内存地址的引用,那么取到的是它生产的bean,而不是它本身。所以我们继续看怎么取到生产的对象的:
FactoryBeanRegistrySupport类的getObjectFromFactoryBean方法
protected Object getObjectFromFactoryBean(FactoryBean> factory, String beanName, boolean shouldPostProcess) {
if (factory.isSingleton() && this.containsSingleton(beanName)) {
synchronized(this.getSingletonMutex()) {
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
object = this.doGetObjectFromFactoryBean(factory, beanName);
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
} else {
if (object != null && shouldPostProcess) {
try {
object = this.postProcessObjectFromFactoryBean(object, beanName);
} catch (Throwable var9) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's singleton object failed", var9);
}
}
this.factoryBeanObjectCache.put(beanName, object != null ? object : NULL_OBJECT);
}
}
return object != NULL_OBJECT ? object : null;
}
} else {
Object object = this.doGetObjectFromFactoryBean(factory, beanName);
if (object != null && shouldPostProcess) {
try {
object = this.postProcessObjectFromFactoryBean(object, beanName);
} catch (Throwable var11) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", var11);
}
}
return object;
}
}
doGetObjectFromFactoryBean:
private Object doGetObjectFromFactoryBean(final FactoryBean> factory, String beanName) throws BeanCreationException {
Object object;
try {
if (System.getSecurityManager() != null) {
AccessControlContext acc = this.getAccessControlContext();
try {
object = AccessController.doPrivileged(new PrivilegedExceptionAction
public Object run() throws Exception {
return factory.getObject();
}
}, acc);
} catch (PrivilegedActionException var6) {
throw var6.getException();
}
} else {
object = factory.getObject();
}
} catch (FactoryBeanNotInitializedException var7) {
throw new BeanCurrentlyInCreationException(beanName, var7.toString());
} catch (Throwable var8) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", var8);
}
if (object == null && this.isSingletonCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName, "FactoryBean which is currently in creation returned null from getObject");
} else {
return object;
}
}
第一个方法就是区分单例还是多例,第二个方法是真真的调用getObject的方法获得FactoryBean生产的对象。从代码中可以看到,具体产生Bean的地方时这个getObject方法,Spring为这个FactoryBean提供了70多个实现,比如Poxy、JDNI、RMI等等。