自定义扩展点
Spring框架提供了许多接口,可以使用它们来定制bean的性质。分组如下:
- 生命周期回调
ApplicationContextAware
和BeanNameAware
- 其他
Aware
接口
生命周期回调
为了与容器对bean生命周期的管理进行交互,可以实现Spring InitializingBean和DisposableBean接口。容器对前者调用afterPropertiesSet(),对后者调用destroy(),让bean在初始化和销毁bean时执行某些操作。
在现代Spring应用程序中,JSR-250 @PostConstruct和@PreDestroy注解通常被认为是接收生命周期回调的最佳实践。使用这些注解意味着你的bean没有耦合到特定于spring的接口。详情请参见使用@PostConstruct和@PreDestroy。
如果不想使用JSR-250注解,但仍然希望消除耦合,请考虑init-method和destroy-method bean定义元数据。
在内部,Spring框架使用BeanPostProcessor实现来处理它可以找到的任何回调接口,并调用适当的方法。如果您需要定制特性或Spring默认不提供的其他生命周期行为,您可以自己实现BeanPostProcessor。有关更多信息,请参见容器扩展点。
除了初始化和销毁回调,spring管理的对象还可能实现Lifecycle接口,以便这些对象可以参与启动和关闭过程,就像容器自己的生命周期驱动的那样。
本节描述生命周期回调接口。
初始化回调
initializingbean接口允许bean在容器设置了bean上所有必要的属性之后执行初始化工作。InitializingBean接口指定了一个方法:
void afterPropertiesSet() throws Exception;
建议你不要使用InitializingBean接口,因为它不必要地将代码与Spring耦合在一起。或者,建议使用@PostConstruct注释或指定POJO初始化方法。在基于xml的配置元数据的情况下,可以使用init-method属性指定具有空无参数签名的方法的名称。通过Java配置,您可以使用@Bean的initMethod属性
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
public class ExampleBean {
public void init() {
// do some initialization work
}
}
前面的示例与下面的示例效果几乎完全相同:
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements InitializingBean {
@Override
public void afterPropertiesSet() {
// do some initialization work
}
}
然而,前面两个示例中的第一个没有将代码与Spring耦合。
销毁回调
实现org.springframework.beans.factory.DisposableBean接口可以让bean在容器被销毁时获得一个回调函数。disablebean接口指定了一个方法:
void destroy() throws Exception;
我们建议你不要使用disablebean回调接口,因为它不必要地将代码与Spring耦合在一起。或者,我们建议使用@PreDestroy注释或指定bean定义支持的泛型方法。对于基于xml的配置元数据,你可以在上使用destroy-method属性。通过Java配置,你可以使用@Bean的destroyMethod属性
<bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
public class ExampleBean {
public void cleanup() {
// do some destruction work (like releasing pooled connections)
}
}
上面的定义几乎与下面的定义具有完全相同的效果:
<bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
public class AnotherExampleBean implements DisposableBean {
@Override
public void destroy() {
// do some destruction work (like releasing pooled connections)
}
}
然而,前面两个定义中的第一个没有将代码与Spring耦合起来。
从Spring 2.5开始,您有三个控制bean生命周期行为的选项:
- InitializingBean和DisposableBean回调接口
- 自定义init()和destroy()方法
- @PostConstruct和@PreDestroy注解。
(执行顺序)使用不同的初始化方法为同一个bean配置的多个生命周期机制如下所示:文章来源:https://www.toymoban.com/news/detail-565222.html
- 用@PostConstruct注释的方法
- 由InitializingBean回调接口定义的afterPropertiesSet()
- 自定义配置的init()方法
Destroy方法的调用顺序相同:文章来源地址https://www.toymoban.com/news/detail-565222.html
- 用@PreDestroy标注的方法
- 由disablebean回调接口定义的destroy()
- 自定义配置的destroy()方法
到了这里,关于Spring中自定义Bean特性的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!