一 . 概述
Bean 的生命周期就是指, Bean 的创建, 初始化, 销毁的整个过程.
spring 帮助我们实现整个过程, 但是提供了很多的回调接口, 我们
可以自己定义这些方法.
一共有四种方式可以实现这些.
二 . 使用 init-method 来实现.
组件:
- public class Person {public Person() {
- System.out.println("构造器在创建对象");
- }
- public void init() {
- System.out.println("我是 init 方法");
- }
- public void destroy() {
- System.out.println("我是销毁方法");
- }
- }
配置类:
- @Configuration
- public class LifeConfig {
- @Bean(initMethod="init",destroyMethod="destroy")
- public Person person() {
- return new Person();
- }
- }
我们使用 @Bean 注解的使用完成指定初始化和销毁方法.
测试类:
- public class LifeTest {
- private static AnnotationConfigApplicationContext context = null;
- @Before
- public void init() {
- context = new AnnotationConfigApplicationContext(LifeConfig.class);
- }
- @Test
- public void test1() {
- }
- @After
- public void close() {
- context .close();
- }
- }
这种方式很不错. 没有什么侵入性.
三 . 实现接口完成
[1] 初始化 实现 InitializingBean 接口
[2] 销毁实现 DisposableBean 接口
这里不做演示, 因为侵入性的方式我们不喜欢用的.
四 . 使用 JSR-250 的方式
我们也不喜欢去使用, 最起码导入这个包就已经够烦人了.
@PostConstroct 注解 @PostConstruct 注解完成
我们也在这里说一下就可以了.
来源: http://www.bubuko.com/infodetail-2619082.html