通过Spring定制Bean生命周期各阶段的性质
通过Spring定制Bean生命周期各阶段的性质
Spring为管理的Bean提供了一系列方法在生命周期各阶段的进行操作的能力与感知Aware的能力,通过这些能力我们能对Bean性质进行定制。
生命周期管理
初始化回调
在容器对Bean完成定义后,Spring通过BeanPostProcessor调用Bean关于生命周期的回调方法,有三种方式对回调方法进行定义,分别为:
-
实现InitializingBean接口 在InitializingBean接口中指定方法:
在void afterPropertiesSet() 中进行初始化设置 该方法将Bean与Spring耦合,不被官方所推荐。
-
xml中在bean标签中配置init-method属性 <bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/> 该方式需要在Bean内定义相应的init方法,或者使用@Bean注解进行配置,设置其initMethod属性,如果需要批量设置,可以在设置: 对方法设置*@PostConstruct*注解 @PostConstruct为JSR-250注解,可以将其配置在方法上,进行初始化调用,源码为: @Documented @Retention (RUNTIME) @Target(METHOD) public @interface PostConstruct { }
销毁回调
-
实现DisposableBean接口 与InitializingBean类似,实现接口中的destroy()方法,同样不被Spring推荐。 xml中在bean标签中配置destroy-method属性 <bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/> 对方法设置*@PreDestroy*注解 @Documented @Retention (RUNTIME) @Target(METHOD) public @interface PreDestroy { }
可以在Bean内设置多种回调方法,Spring也会依次调用,顺序为:
1.JSR-250注解
2.接口实现
3.xml或@Bean配置的init初始化方法
Aware
通过Aware的一系列实现可以获取Bean容器的基础设施如:
-
ApplicationContextAware,获取ApplicationContext BeanNameAware,获取容器内的bean名称 更多可见: