前言
众所周知 Spring 的核心思想是IOC(控制与反转),而控制与反转都是依赖于容器来进行的。
Spring Boot 更是封装了Spring ,遵循 约定大于配置 的原则,实现了自动装配的机制。很多时候我们只需要引入一个starter ,就可以使用整个模块的功能。
在日常开发工作中,我们可能会需要在容器启动过程或容器启动完成之后做一些初始化工作。这时候我们就需要结合容器的启动过程和spring提供的拓展点来做一些自定义的内容。今天主要介绍的就是spring提供的一些拓展点。
全部拓展点的调用时序
拓展点加载顺序
1. ApplicationContextInitializer
这是整个 spring 容器在刷新之前初始化 ConfigurableApplicationContext 的回调接口。在容器刷新之前会调用此类的 initialize 方法。
示例
@Slf4j public class TestApplicationContextInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { log.info("实现 ApplicationContextInitializer 执行顺序为 {}", OrderUtils.getOrder()); } }
不同于一般的扩展点,只要生成相应的bean即可生效。因为该拓展点执行时,spring容器还没有初始化完成,因此想要自己的拓展生效,需要使用一下三种方式:
在启动类中添加初始化器
@SpringBootApplication @MapperScan(basePackages = {"com.example.hellosecurity.mapper"}) public class HellosecurityApplication { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication (HellosecurityApplication.class); springApplication.addInitializers(new TestApplicationContextInitializer()); springApplication.run(); //SpringApplication.run(HellosecurityApplication.class, args); } }
在 resources/META-INF/spring.factories 中配置
@SpringBootApplication @MapperScan(basePackages = {"com.example.hellosecurity.mapper"}) public class HellosecurityApplication { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication (HellosecurityApplication.class); springApplication.addInitializers(new TestApplicationContextInitializer()); springApplication.run(); //SpringApplication.run(HellosecurityApplication.class, args); } }
在yml文件 或启动参数中添加变量 context.initializer.classes=com.example.hellosecurity.component.TestApplicationContextInitializer
使用场景
用户可以在整个spring容器还没被初始化之前做一些事情。
可以想到的场景可能为,在最开始激活一些配置,或者利用这时候class还没被类加载器加载的时机,进行动态字节码注入等操作
2. BeanDefinitionRegistryPostProcessor
这个接口在读取项目中的beanDefinition之后执行,提供一个补充的扩展点
示例
@Slf4j @Component public class TestBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { log.info("实现 BeanDefinitionRegistryPostProcessor 执行顺序为 {}", OrderUtils.getOrder()); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { log.info("实现 BeanDefinitionRegistryPostProcessor 执行顺序为 {}", OrderUtils.getOrder()); } }
使用场景
可以在这里动态注册自己的beanDefinition,可以加载classpath之外的bean
3. BeanFactoryPostProcessor
这个接口是beanFactory的扩展接口,调用时机在spring在读取beanDefinition信息之后,实例化bean之前
示例
@Slf4j @Component public class TestBeanFactoryPostProcessor implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { log.info("实现 BeanFactoryPostProcessor 执行顺序为 {}", OrderUtils.getOrder()); } }
使用场景
用户可以通过实现这个扩展接口来自行处理一些东西,比如修改已经注册的beanDefinition的元信息
4. InstantiationAwareBeanPostProcessor
该接口继承了BeanPostProcess接口,区别如下:
BeanPostProcess接口只在bean的初始化阶段进行扩展(注入spring上下文前后),而InstantiationAwareBeanPostProcessor接口在此基础上增加了3个方法,把可扩展的范围增加了实例化阶段和属性注入阶段。
该类主要的扩展点有以下5个方法,主要在bean生命周期的两大阶段:实例化阶段和初始化阶段,下面一起进行说明,按调用顺序为:
postProcessBeforeInstantiation:实例化bean之前,相当于new这个bean之前
postProcessAfterInstantiation:实例化bean之后,相当于new这个bean之后
postProcessPropertyValues:bean已经实例化完成,在属性注入时阶段触发,@Autowired,@Resource等注解原理基于此方法实现
postProcessBeforeInitialization:初始化bean之前,相当于把bean注入spring上下文之前
postProcessAfterInitialization:初始化bean之后,相当于把bean注入spring上下文之后
示例
** * 每个bean的实例化 和 初始化过程都会执行一遍 * @Author: * @Date: 2023/6/26 * @Version: V1.0 * @Description: **/ @Slf4j @Component public class TestInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor { @Override public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException { log.info("实现 InstantiationAwareBeanPostProcessor 执行顺序为 {}", OrderUtils.getOrder()); return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation (beanClass, beanName); } @Override public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { log.info("实现 InstantiationAwareBeanPostProcessor 执行顺序为 {}", OrderUtils.getOrder()); return InstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation (bean, beanName); } @Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException { log.info("实现 InstantiationAwareBeanPostProcessor 执行顺序为 {}", OrderUtils.getOrder()); return InstantiationAwareBeanPostProcessor.super.postProcessProperties (pvs, bean, beanName); } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { log.info("实现 InstantiationAwareBeanPostProcessor 执行顺序为 {}", OrderUtils.getOrder()); return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInitialization (bean, beanName); } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { log.info("实现 InstantiationAwareBeanPostProcessor 执行顺序为 {}", OrderUtils.getOrder()); return InstantiationAwareBeanPostProcessor.super.postProcessAfterInitialization (bean, beanName); } }
使用场景
这个扩展点非常有用 ,无论是写中间件和业务中,都能利用这个特性。比如对实现了某一类接口的bean在各个生命期间进行收集,或者对某个类型的bean进行统一的设值等等。
需要注意的是,该拓展点会在每个bean的初始化阶段都会执行一遍。
5. SmartInstantiationAwareBeanPostProcessor
该扩展接口有3个触发点方法:
predictBeanType:该触发点发生在postProcessBeforeInstantiation之前(在图上并没有标明,因为一般不太需要扩展这个点),这个方法用于预测Bean的类型,返回第一个预测成功的Class类型,如果不能预测返回null;当你调用BeanFactory.getType(name)时当通过bean的名字无法得到bean类型信息时就调用该回调方法来决定类型信息。
determineCandidateConstructors:该触发点发生在postProcessBeforeInstantiation之后,用于确定该bean的构造函数之用,返回的是该bean的所有构造函数列表。用户可以扩展这个点,来自定义选择相应的构造器来实例化这个bean。
getEarlyBeanReference:该触发点发生在postProcessAfterInstantiation之后,当有循环依赖的场景,当bean实例化好之后,为了防止有循环依赖,会提前暴露回调方法,用于bean实例化的后置处理。这个方法就是在提前暴露的回调方法中触发。
示例
@Slf4j @Component public class TestSmartInstantiationAwareBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor { @Override public Class<?> predictBeanType(Class<?> beanClass, String beanName) throws BeansException { log.info("实现 SmartInstantiationAwareBeanPostProcessor 执行顺序为 {}", OrderUtils.getOrder()); return SmartInstantiationAwareBeanPostProcessor.super.predictBeanType (beanClass, beanName); } @Override public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException { log.info("实现 SmartInstantiationAwareBeanPostProcessor 执行顺序为 {}", OrderUtils.getOrder()); return SmartInstantiationAwareBeanPostProcessor.super.determineCandidateConstructors (beanClass, beanName); } @Override public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException { log.info("实现 SmartInstantiationAwareBeanPostProcessor 执行顺序为 {}", OrderUtils.getOrder()); return SmartInstantiationAwareBeanPostProcessor.super.getEarlyBeanReference (bean, beanName); } }
使用场景
该拓展点使用的地方较少,或者说能够替代的拓展点比较多。
需要注意的是,该拓展点也会在每个bean初始化的过程中都执行一遍。
6. BeanFactoryAware
这个类只有一个触发点,发生在bean的实例化之后,注入属性之前,也就是Setter之前。这个类的扩展点方法为setBeanFactory,可以拿到BeanFactory这个属性。
示例
@Component @Slf4j public class TestBeanFactoryAware implements BeanFactoryAware { @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { HelloUserDetailService userDetailService = beanFactory.getBean (HelloUserDetailService.class); UserDetails userDetails = userDetailService.loadUserByUsername("admin"); System.out.println(JSONUtil.toJsonStr(userDetails)); log.info("实现 BeanFactoryAware 执行顺序为 {}", OrderUtils.getOrder()); } }
使用场景
可以在bean实例化之后,但还未初始化之前,拿到 BeanFactory,在这个时候,可以对每个bean作特殊化的定制。 也或者可以把BeanFactory拿到进行缓存,日后使用。
7. ApplicationContextAwareProcessor
该类本身并没有扩展点,但是该类内部却有6个扩展点可供实现 ,这些类触发的时机在bean实例化之后,初始化之前
示例
private void invokeAwareInterfaces(Object bean) { if (bean instanceof EnvironmentAware) { ((EnvironmentAware) bean).setEnvironment (this.applicationContext.getEnvironment()); } if (bean instanceof EmbeddedValueResolverAware) { ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver (this.embeddedValueResolver); } if (bean instanceof ResourceLoaderAware) { ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext); } if (bean instanceof ApplicationEventPublisherAware) { ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher (this.applicationContext); } if (bean instanceof MessageSourceAware) { ((MessageSourceAware) bean).setMessageSource(this.applicationContext); } if (bean instanceof ApplicationStartupAware) { ((ApplicationStartupAware) bean).setApplicationStartup (this.applicationContext.getApplicationStartup()); } if (bean instanceof ApplicationContextAware) { ((ApplicationContextAware) bean).setApplicationContext (this.applicationContext); } }
使用场景
可以看到,该类用于执行各种驱动接口,在bean实例化之后,属性填充之后,通过执行以上红框标出的扩展接口,来获取对应容器的变量。所以这里应该来说是有6个扩展点,这里就放一起来说了
EnvironmentAware:用于获取EnviromentAware的一个扩展类,这个变量非常有用, 可以获得系统内的所有参数。当然个人认为这个Aware没必要去扩展,因为spring内部都可以通过注入的方式来直接获得。
EmbeddedValueResolverAware:用于获取StringValueResolver的一个扩展类, StringValueResolver用于获取基于String类型的properties的变量,一般我们都用@Value的方式去获取,如果实现了这个Aware接口,把StringValueResolver缓存起来,通过这个类去获取String类型的变量,效果是一样的。
ResourceLoaderAware:用于获取ResourceLoader的一个扩展类,ResourceLoader可以用于获取classpath内所有的资源对象,可以扩展此类来拿到ResourceLoader对象。
ApplicationEventPublisherAware:用于获取ApplicationEventPublisher的一个扩展类,ApplicationEventPublisher可以用来发布事件,结合ApplicationListener来共同使用,下文在介绍ApplicationListener时会详细提到。这个对象也可以通过spring注入的方式来获得。
MessageSourceAware:用于获取MessageSource的一个扩展类,MessageSource主要用来做国际化。
ApplicationContextAware:用来获取ApplicationContext的一个扩展类,ApplicationContext应该是很多人非常熟悉的一个类了,就是spring上下文管理器,可以手动的获取任何在spring上下文注册的bean,我们经常扩展这个接口来缓存spring上下文,包装成静态方法。同时ApplicationContext也实现了BeanFactory,MessageSource,ApplicationEventPublisher等接口,也可以用来做相关接口的事情。
8. BeanNameAware
这个类也是Aware扩展的一种,触发点在bean的初始化之前,也就是postProcessBeforeInitialization之前,这个类的触发点方法只有一个:setBeanName
示例
@Slf4j @Component public class TestBeanNameAware implements BeanNameAware { @Override public void setBeanName(String name) { log.info("实现 BeanNameAware 执行顺序为 {}", OrderUtils.getOrder()); } }
使用场景
用户可以通过实现这个扩展接口来自行处理一些东西,比如修改已经注册的beanDefinition的元信息
9. PostConstruct
这个并不算一个扩展点,其实就是一个标注。其作用是在bean的初始化阶段,如果对一个方法标注了@PostConstruct,会先调用这个方法。这里重点是要关注下这个标准的触发点,这个触发点是在postProcessBeforeInitialization之后,InitializingBean.afterPropertiesSet之前
示例
@Slf4j @Component public class TestBeanNameAware implements BeanNameAware { @Override public void setBeanName(String name) { log.info("实现 BeanNameAware 执行顺序为 {}", OrderUtils.getOrder()); } @PostConstruct public void init() { log.info("@PostConstruct 执行顺序为 {}", OrderUtils.getOrder()); } }
使用场景
用户可以对某一方法进行标注,来进行初始化某一个属性
10. InitializingBean
这个类,顾名思义,也是用来初始化bean的。InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。这个扩展点的触发时机在postProcessAfterInitialization之前。
示例
@Component @Slf4j public class TestInitializingBean implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { log.info("实现 InitializingBean 执行顺序为 {}", OrderUtils.getOrder()); } }
使用场景
用户实现此接口,来进行系统启动的时候一些业务指标的初始化工作。
11. FactoryBean
一般情况下,Spring通过反射机制利用bean的class属性指定支线类去实例化bean,在某些情况下,实例化Bean过程比较复杂,如果按照传统的方式,则需要在bean中提供大量的配置信息。配置方式的灵活性是受限的,这时采用编码的方式可能会得到一个简单的方案。Spring为此提供了一个org.springframework.bean.factory.FactoryBean的工厂类接口,用户可以通过实现该接口定制实例化Bean的逻辑。FactoryBean接口对于Spring框架来说占用重要的地位,Spring自身就提供了70多个FactoryBean的实现。它们隐藏了实例化一些复杂bean的细节,给上层应用带来了便利。从Spring3.0开始,FactoryBean开始支持泛型,即接口声明改为FactoryBean<T>的形式
示例
@Slf4j @Component public class TestFactoryBean implements FactoryBean<TestFactoryBean.TestFactoryBeanInnerBean> { @Override public TestFactoryBeanInnerBean getObject() throws Exception { log.info("实现 FactoryBean 执行顺序为 {}", OrderUtils.getOrder()); return new TestFactoryBeanInnerBean(); } @Override public Class<?> getObjectType() { //日志次数太多 //log.info("实现 FactoryBean 执行顺序为 {}", OrderUtils.getOrder()); return TestFactoryBean.TestFactoryBeanInnerBean.class; } @Override public boolean isSingleton() { return true; } public static class TestFactoryBeanInnerBean{ } }
使用场景
用户可以扩展这个类,来为要实例化的bean作一个代理,比如为该对象的所有的方法作一个拦截,在调用前后输出一行log,模仿ProxyFactoryBean的功能
12. SmartInitializingSingleton
这个接口中只有一个方法afterSingletonsInstantiated,其作用是是 在spring容器管理的所有单例对象(非懒加载对象)初始化完成之后调用的回调接口。其触发时机为postProcessAfterInitialization之后。
示例
@Slf4j @Component public class TestSmartInitializingSingleton implements SmartInitializingSingleton { @Override public void afterSingletonsInstantiated() { log.info("实现 SmartInitializingSingleton 执行顺序为 {}", OrderUtils.getOrder()); } }
使用场景
用户可以扩展此接口在对所有单例对象初始化完毕后,做一些后置的业务处理。
13. CommandLineRunner
这个接口也只有一个方法:run(String... args),触发时机为整个项目启动完毕后,自动执行。如果有多个CommandLineRunner,可以利用@Order来进行排序。
示例
@Slf4j @Component @Order(1) public class TestCommandLineRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { log.info("实现 CommandLineRunner 执行顺序为 {}", OrderUtils.getOrder()); } }
使用场景
用户扩展此接口,进行启动项目之后一些业务的预处理。
14. DisposableBean
这个扩展点也只有一个方法:destroy(),其触发时机为当此对象销毁时,会自动执行这个方法。比如说运行applicationContext.registerShutdownHook时,就会触发这个方法
示例
@Slf4j @Component public class TestDisposableBean implements DisposableBean { @Override public void destroy() throws Exception { log.info("实现 FactoryBean 执行顺序为 {}", OrderUtils.getOrder()); } }
使用场景
用户可以通过实现这个扩展接口来自行处理一些东西,比如修改已经注册的beanDefinition的元信息
15.ApplicationListener
准确的说,这个应该不算spring&springboot当中的一个扩展点,ApplicationListener可以监听某个事件的event,触发时机可以穿插在业务方法执行过程中,用户可以自定义某个业务事件。但是spring内部也有一些内置事件,这种事件,可以穿插在启动调用中。我们也可以利用这个特性,来自己做一些内置事件的监听器来达到和前面一些触发点大致相同的事情。
接下来罗列下spring主要的内置事件:
ContextRefreshedEvent ApplicationContext 被初始化或刷新时,该事件被发布。这也可以在ConfigurableApplicationContext接口中使用 refresh()方法来发生。此处的初始化是指:所有的Bean被成功装载,后处理Bean被检测并激活,所有Singleton Bean 被预实例化,ApplicationContext容器已就绪可用。
ContextStartedEvent 当使用 ConfigurableApplicationContext (ApplicationContext子接口)接口中的 start() 方法启动 ApplicationContext时,该事件被发布。你可以调查你的数据库,或者你可以在接受到这个事件后重启任何停止的应用程序。
ContextStoppedEvent 当使用 ConfigurableApplicationContext接口中的 stop()停止ApplicationContext 时,发布这个事件。你可以在接受到这个事件后做必要的清理的工作
ContextClosedEvent 当使用 ConfigurableApplicationContext接口中的 close()方法关闭 ApplicationContext 时,该事件被发布。一个已关闭的上下文到达生命周期末端;它不能被刷新或重启
RequestHandledEvent 这是一个 web-specific 事件,告诉所有 bean HTTP 请求已经被服务。只能应用于使用DispatcherServlet的Web应用。在使用Spring作为前端的MVC控制器时,当Spring处理用户请求结束后,系统会自动触发该事件
示例
@Slf4j @Component public class TestApplicationListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { log.info("实现 ApplicationListener 执行顺序为 {}", OrderUtils.getOrder()); } }
另外一种方式(推荐)
@Slf4j @Component public class TestApplicationListener2{ @EventListener(ContextRefreshedEvent.class) public void log(ContextRefreshedEvent event) { log.info("使用@EventListener 执行顺序为 {}", OrderUtils.getOrder()); } }
使用场景
有些重要任务,需要优雅关闭线程池等
发表评论 取消回复