简介 最近空闲重新学习了一下Spring,之前只知道ApplicationContext和BeanFactory都是Spring的容器,且ApplicationContext对BeanFactory做了增强,当时其具体的实现不了解,知道最近在自己突发奇想,想使用BeanFactory去读取注解(@Bean)定义的类时才从源码中了解到相关内容,其是本质就是对BeanPostProcessor和BeanFactoryPostProcessor的分析。
核心定义 Spring的对象分为BeanDefinition和实例化对象,BeanDefinition就是Spring读取xml文件,把xml文件中配置的类信息转换成Spring的类的元信息,而实例化就是根据BeanDefinition中的信息将对象实例化成java对象的过程,而BeanDefinition和Bean实例化的中的扩展点分别为BeanFactoryPostProcessor和BeanPostProcessor.
问题起因 在使用BeanFactory进行容器创建的时候使用BeanDefinitionReader去读取xml中的配置信息,并把配置信息中的对象转换成BeanDefinition,如下
1 2 3 DefaultListableBeanFactory defaultListableBeanFactory=new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader=new XmlBeanDefinitionReader(defaultListableBeanFactory); reader.loadBeanDefinitions("spring.xml");
这时我思考为何日常使用的SpringBoot中可以使用@Configuration和@Bean的方式去读取我们使用代码配置的Bean信息?如下
1 2 3 4 5 6 7 8 9 @Configuration public class ConfigOut { @Bean public User user(){ return new User(); } }
于是第一反应就和xmlRead类似,于是找到一个AnnotatedBeanDefinitionReader模仿XmlBeanDefinitionReader试一下,结果发现是不行的,BeanFactory中并不能找到User对象,且AnnotatedBeanDefinitionReader并没有继承BeanDefinitionReader,只是名字像而已,而使用ApplicationContext却可以正常读取到User对象
1 2 3 4 AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(); applicationContext.register(Main.class); applicationContext.refresh(); applicationContext.getBean(User.class);
分析过程 既然问题起因是@Bean这个注解,于是我全局搜索@Bean这个对象在哪里被调用的,于是找到ConfigurationClassBeanDefinitionReader其有一个loadBeanDefinitionsForBeanMethod的方法处理了@Bean对象实例化的步骤,由于其是一个default作用域的包我们无法调用,于是我们又去寻找谁调用了ConfigurationClassBeanDefinitionReader,于是我们又找到了ConfigurationClassPostProcessor,其是一个BeanFactoryPostProcessor,我们进入源码查看注解看到一句话
1 2 Factory hook that allows for custom modification of an application context's bean definitions
*大意就是该类允许对application中BeanDefinition做一些自定义的扩展,我们注意到一句话,里面说的application 中的容器,所以BeanFactoryPostProcessor针对的是application生命周期的扩展,而BeanFactory中没有这个周期,所以自然BeanFactory也无法自动扫描@Bean *
那BeanFactoryPostProcessor又是在哪里被注册和调用的呢,我们继续寻找BeanFactoryPostProcessor的引用于是找到PostProcessorRegistrationDelegate下的方法invokeBeanFactoryPostProcessors,其中调用方法,这里就是将所有BeanFactoryPostProcessor依次调用
1 2 3 4 5 6 7 8 9 10 /** * Invoke the given BeanFactoryPostProcessor beans. */ private static void invokeBeanFactoryPostProcessors( Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) { for (BeanFactoryPostProcessor postProcessor : postProcessors) { postProcessor.postProcessBeanFactory(beanFactory); } }
而invokeBeanFactoryPostProcessors又在AbstractApplicationContext下的invokeBeanFactoryPostProcessors被调用,其又在Application下的refresh中被调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. prepareRefresh(); // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // Initialize message source for this context. initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh();
那么我们这里得出了结论,BeanFactoryPostProcessor的是作用在Application下的方法,其是对BeanFactory下的BeanDefinition的增强,我们上面看到的是对注册的Bean对象包含@Bean注解的方法做解析,并且将其注册到Spring,而之前我们使用的是BeanFactory当做容器来直接使用,自然就没有可以针对处理@Bean注解的方法,那么有没有一种可以使BeanFactory也可以识别到@Bean注解的方法呢,答案也很简单就是我们手动调用一下ConfigurationClassPostProcessor完成一下BeanFactory的增强即可
1 2 3 4 DefaultListableBeanFactory defaultListableBeanFactory=new DefaultListableBeanFactory(); ConfigurationClassPostProcessor processor=new ConfigurationClassPostProcessor(); processor.postProcessBeanFactory(defaultListableBeanFactory); defaultListableBeanFactory.getBean("user");
BeanPostProcessor 我们进入其源码可以看到第一句话,意思为其对bean实例化做扩展,就是我们可以控制实例化时其初始化值的一些行为,比如改变bean的值
1 Factory hook that allows for custom modification of new bean instances
相对于BeanFactoryPostProcessor,其作用域是在Bean的实例化阶段,我们可以看下Spring中对其应用,jdbc是我们日常开发中经常用到的包(org.springframework.boot.autoconfigure.jdbc),其也是实现了BeanPostProcessor,其在Bean实例化时做了增强每次获取的Bean对象如果是DataSource的就自动获取DataSourceInitializerInvoker来返回,从而达到屏蔽DataSource实现的目的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 class DataSourceInitializerPostProcessor implements BeanPostProcessor, Ordered { @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE + 1; } @Autowired private BeanFactory beanFactory; @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof DataSource) { // force initialization of this bean as soon as we see a DataSource this.beanFactory.getBean(DataSourceInitializerInvoker.class); } return bean; } }
而DataSourceInitializerPostProcessor又是在DataSourceInitializationConfiguration中注册的,ImportBeanDefinitionRegistrar为每次Spring初始化时都会去调用registerBeanDefinitions,从注入DataSourceInitializerPostProcessor,而在Application启动时调用reflush都和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 @Configuration(proxyBeanMethods = false) @Import({ DataSourceInitializerInvoker.class, DataSourceInitializationConfiguration.Registrar.class }) class DataSourceInitializationConfiguration { /** * {@link ImportBeanDefinitionRegistrar} to register the * {@link DataSourceInitializerPostProcessor} without causing early bean instantiation * issues. */ static class Registrar implements ImportBeanDefinitionRegistrar { private static final String BEAN_NAME = "dataSourceInitializerPostProcessor"; @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { if (!registry.containsBeanDefinition(BEAN_NAME)) { GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(DataSourceInitializerPostProcessor.class); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); // We don't need this one to be post processed otherwise it can cause a // cascade of bean instantiation that we would rather avoid. beanDefinition.setSynthetic(true); registry.registerBeanDefinition(BEAN_NAME, beanDefinition); } } } }
而上文中Application启动时调用reflush方法在application初始化时都会完成注册
1 2 // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory);
总结 Application底层使用了BeanFactory来充当容器,当时其有许多增强类来提升了很多功能,比如注解,扫描等,其中BeanFactoryPostProcessor作用在Bean定义阶段BeanPostProcessor作用在Bean实例化阶段。