spring之FactoryBean接口
程序员文章站
2022-03-19 10:59:55
...
//该接口主要用于从spring中获取bean的时候如果实现了该接口会直接调用该接口中的getObject来获取bean public interface FactoryBean<T> { T getObject() throws Exception; Class<?> getObjectType(); boolean isSingleton(); } /** 其在获取bean的时候判断是否实现了FactoryBean接口从这也可以看出如果一个类实现了FactoryBean接口但是我们想要返回他本身的实例, 我们可以在获取bean的时候在名字前面加&符号即可。 */ protected Object getObjectForBeanInstance( Object beanInstance, String name, String beanName, RootBeanDefinition mbd) { if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) { throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass()); } //判断是否实现了FactoryBean接口或者以&开头 if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) { return beanInstance; } Object object = null; if (mbd == null) { object = getCachedObjectForFactoryBean(beanName); } if (object == null) { // Return bean instance from factory. FactoryBean<?> factory = (FactoryBean<?>) beanInstance; // Caches object obtained from FactoryBean if it is a singleton. if (mbd == null && containsBeanDefinition(beanName)) { mbd = getMergedLocalBeanDefinition(beanName); } boolean synthetic = (mbd != null && mbd.isSynthetic()); object = getObjectFromFactoryBean(factory, beanName, !synthetic); } return object; } //这是从FactoryBean获取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 { object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return factory.getObject(); } }, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { 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); } if (object == null && isSingletonCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } 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; }
推荐阅读
-
Springboot源码分析之Spring循环依赖揭秘
-
Spring5源码解析4-refresh方法之invokeBeanFactoryPostProcessors
-
spring boot2.0.4集成druid,用jmeter并发测试工具调用接口,druid查看监控的结果
-
深入了解Spring中的FactoryBean
-
JSP开发之Spring方法注入之替换方法实现
-
JSP 开发之Spring Boot 动态创建Bean
-
Spring boot 总结之跨域处理cors的方法
-
Spring学习之Bean的装配多种方法
-
Spring学习之开发环境搭建的详细步骤
-
Spring学习之依赖注入的方法(三种)