曹工杂谈:为什么很少需要改Spring源码,因为扩展点太多了,说说Spring的后置处理器
前言
最近发了好几篇,都是覆盖框架源码,但是spring的代码,我是从没覆盖过,毕竟,如果方便扩展,没谁想去改源码,而spring就是不需要改源码的那个,真的是“对扩展开放,对修改关闭”的典范。
就我说曾经用过的,spring的扩展点,就包括了listener
、beanFactoryPostProcessor
、beanPostProcessor
,而spring boot的扩展点,除了properties
、yml
、java config
覆盖自动配置、org.springframework.boot.CommandLineRunner
,还包括了META-INF
下的spring.factory
等。
眼下就有以前的一个例子:
这次,只简单说说后置处理器,主要是beanFactoryPostProcessor
、beanPostProcessor
。
先说说beanFactoryPostProcessor
这两个比较像,都是后置处理器,但是处理的对象不同,前者是针对beanFactory,后者是针对bean实例。
beanFactoryPostProcessor
的注释如下:
Allows for custom modification of an application context's bean definitions, adapting the bean property values of the context's underlying bean factory. Application contexts can auto-detect BeanFactoryPostProcessor beans in their bean definitions and apply them before any other beans get created. Useful for custom config files targeted at system administrators that override bean properties configured in the application context. See PropertyResourceConfigurer and its concrete implementations for out-of-the-box solutions that address such configuration needs. A BeanFactoryPostProcessor may interact with and modify bean definitions, but never bean instances. Doing so may cause premature bean instantiation, violating the container and causing unintended side-effects. If bean instance interaction is required, consider implementing BeanPostProcessor instead.
简单来说,允许对bean definition
进行修改。