FactoryBean与BeanFactory:
这俩货在拼写上很是相似,很多同学在看IOC源码或者其他地方并不能分清有啥区别,前面的IOC源码中我简单说过,现在统一简单来讲一下:
- FactoryBean:是一个Java Bean,但是它是一个能生产对象的工厂Bean,它的实现和工厂模式及修饰器模式很像。比如下:我们把bean比作是人,那么FactoryBean可以算是一个女人,首先它本身也是一个人,但它能够生产人。【挺尴尬的比喻】。
- BeanFactory:这就是一个Factory,是一个IOC容器或者叫对象工厂,它里面存着很多的bean。还用上面那个比如:如果bean是人,那么它可以理解成学校,学校里面很多人,学校管理这么多的人。
FactoryBean在IOC的应用:
前面我们在看IOC源码的时候,发现即使我们已经创建出来了对象的实例,还是要走一个方法再去处理下,这里就是对FactoryBean的处理,因为它可以产生对象,所以你getBean的时候取到的不是它本身,而是通过它生成的产品。【如果要取它本身,getBean(&+beanName)】 我们先来回忆下IOC源码中那个处理FactoryBean的简略代码:
代码1.1:AbstractBeanFactory类的dogetBean方法
- protected <T> T doGetBean(
- final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
- throws BeansException {
- <span style="white-space:pre"> </span>...
- if (sharedInstance != null && args == null) {
- ...
- bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
- }
- else {
- <span style="white-space:pre"> </span> // Create bean instance.
- if (mbd.isSingleton()) {
- sharedInstance = getSingleton(beanName, new ObjectFactory() {
- public Object getObject() throws BeansException {
- try {
- return createBean(beanName, mbd, args);
- }
- catch (BeansException ex) {
- destroySingleton(beanName);
- throw ex;
- }
- }
- });
- bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
- }
- else if (mbd.isPrototype()) {
- Object prototypeInstance = null;
- try {
- beforePrototypeCreation(beanName);
- prototypeInstance = createBean(beanName, mbd, args);
- }
- finally {
- afterPrototypeCreation(beanName);
- }
- bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
- }
- else {
- String scopeName = mbd.getScope();
- final Scope scope = this.scopes.get(scopeName);
- try {
- Object scopedInstance = scope.get(beanName, new ObjectFactory() {
- public Object getObject() throws BeansException {
- beforePrototypeCreation(beanName);
- try {
- return createBean(beanName, mbd, args);
- }
- finally {
- afterPrototypeCreation(beanName);
- }
- }
- });
- bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
- }
- }
- }
- <span style="white-space:pre"> </span>...
- return (T) bean;
- }
代码1.2:AbstractBeanFactory类的getObjectForBeanInstance方法
- protected Object getObjectForBeanInstance(
- Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
- //如果是对FactoryBean的解引用,但bean对象不是FactoryBean,抛出异常
- if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
- throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
- }
- //如果Bean实例不是FactoryBean,或者指定名称是FactoryBean的解引用,也就是普通的bean调用,则直接返回当前的Bean实例
- if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
- return beanInstance;
- }
- //处理对FactoryBean的调用
- Object object = null;
- if (mbd == null) {
- //从Bean工厂缓存中获取给定名称的实例对象
- object = getCachedObjectForFactoryBean(beanName);
- }
- if (object == null) {
- // Return bean instance from factory.
- FactoryBean factory = (FactoryBean) beanInstance;
- //如果从Bean工厂生产的Bean是单态模式的,则缓存
- if (mbd == null && containsBeanDefinition(beanName)) {
- mbd = getMergedLocalBeanDefinition(beanName);
- }
- boolean synthetic = (mbd != null && mbd.isSynthetic());
- //调用FactoryBeanRegistrySupport类的getObjectFromFactoryBean方法,实现FactoryBean生产Bean对象实例的过程
- object = getObjectFromFactoryBean(factory, beanName, !synthetic);
- }
- return object;
- }
Dereference(解引用):一个在C/C++中应用的比较多术语,在C++中,“*”是解引用符号,“&”是引用符号。
解引用:变量所指向的是所引用对象的本身数据,而不是对象的内存地址。
上面的代码可以看到,对于大多数bean的getBean,一般走到第二步就返回了,也就是说我们创建的Bean对象就是想要的bean,但对于FactoryBean的创建,如果是对内存地址的引用,那么取到的是它生产的bean,而不是它本身。所以我们继续看怎么取到生产的对象的:
代码1.3:FactoryBeanRegistrySupport类的getObjectFromFactoryBean方法
- // Bean工厂生产Bean实例对象
- protected Object getObjectFromFactoryBean(FactoryBean factory,
- String beanName, boolean shouldPostProcess) {
- // Bean工厂是单态模式,并且Bean工厂缓存中存在指定名称的Bean实例对象
- if (factory.isSingleton() && containsSingleton(beanName)) {
- synchronized (getSingletonMutex()) {
- // 直接从Bean工厂缓存中获取指定名称的Bean实例对象
- Object object = this.factoryBeanObjectCache.get(beanName);
- // Bean工厂缓存中没有指定名称的实例对象,则生产该实例对象
- if (object == null) {
- // 调用Bean工厂的getObject方法生产指定Bean的实例对象
- object = doGetObjectFromFactoryBean(factory, beanName,
- shouldPostProcess);
- // 将生产的实例对象添加到Bean工厂缓存中
- this.factoryBeanObjectCache.put(beanName,
- (object != null ? object : NULL_OBJECT));
- }
- return (object != NULL_OBJECT ? object : null);
- }
- }
- // 调用Bean工厂的getObject方法生产指定Bean的实例对象
- else {
- return doGetObjectFromFactoryBean(factory, beanName,
- shouldPostProcess);
- }
- }
- //调用Bean工厂的getObject方法生产指定Bean的实例对象
- private Object doGetObjectFromFactoryBean(
- final FactoryBean factory, final String beanName, final boolean shouldPostProcess)
- throws BeanCreationException {
- Object object;
- try {
- if (System.getSecurityManager() != null) {
- AccessControlContext acc = getAccessControlContext();
- try {
- //实现PrivilegedExceptionAction接口的匿名内置类
- //根据JVM检查权限,然后决定BeanFactory创建实例对象
- object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
- public Object run() throws Exception {
- //调用BeanFactory接口实现类的创建对象方法
- return factory.getObject();
- }
- }, acc);
- }
- catch (PrivilegedActionException pae) {
- throw pae.getException();
- }
- }
- else {
- //调用BeanFactory接口实现类的创建对象方法
- object = factory.getObject();
- }
- }
- catch (FactoryBeanNotInitializedException ex) {
- throw new BeanCurrentlyInCreationException(beanName, ex.toString());
- }
- catch (Throwable ex) {
- throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
- }
- //创建出来的实例对象为null,或者因为单态对象正在创建而返回null
- if (object == null && isSingletonCurrentlyInCreation(beanName)) {
- throw new BeanCurrentlyInCreationException(
- beanName, "FactoryBean which is currently in creation returned null from getObject");
- }
- //为创建出来的Bean实例对象添加BeanPostProcessor后置处理器
- if (object != null && shouldPostProcess) {
- try {
- object = postProcessObjectFromFactoryBean(object, beanName);
- }
- catch (Throwable ex) {
- throw new BeanCreationException(beanName, "Post-processing of the FactoryBean's object failed", ex);
- }
- }
- return object;
- }
FactoryBean的举例理解
我们先来看下FactoryBean的接口定义:
- <span style="white-space:pre"> </span>public interface FactoryBean<T> {
- //返回由FactoryBean创建的bean实例,如果isSingleton()返回true,则该实例会放到Spring容器中单实例缓存池中。
- T getObject() throws Exception;
- //返回FactoryBean创建的bean类型。
- Class<?> getObjectType();
- //返回由FactoryBean创建的bean实例的作用域是singleton还是prototype。
- boolean isSingleton();
- }
我们下面就通过一个简单的例子来体验下getObject方法【讲道理,这里实际意义不多,重在理解方法含义】
假如:我们有个Person对象,里面包含 name,address,age。set、get方法不写了
- public class Person {
- private String name;
- private String address;
- private int age;
- }
- <bean id="personBean" class="com.gh.MavenTest.Person">
- <property name="name" value="gh1" />
- <property name="address" value="address1" />
- <property name="age" value="28" />
- </bean>
- public class PersonFactoryBean implements FactoryBean<Person>{
- private String personInfo;
- public Person getObject() throws Exception {
- Person person = new Person () ;
- String [] infos = personInfo.split ( "," ) ;
- person.setName(infos[0]);
- person.setAddress(infos[1]);
- person.setAge(Integer.parseInt(infos[2]));
- return person;
- }
- public Class<Person> getObjectType() {
- return Person.class;
- }
- public boolean isSingleton() {
- return true;
- }
- }
- <bean id="personFactory" class="com.hik.MavenTest.PersonFactory">
- <property name="personInfo" value="gh2,address2,22"></property>
- </bean>
通过上面的小案例的代码,我们可以看到如果一个类实现了FactoryBean接口,那么getBean得到的不是他本身了,而是它所产生的对象,如果我们希望得到它本身,只需要加上&符号即可。至于FactoryBean的实际应用,需要大家去发现理解,后面如果有机会会继续聊聊这个东西。
转自:https://blog.csdn.net/u013185616/article/details/52335864/