一 .概述
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(); } }
这种方式很不错.没有什么侵入性,我们在@Bean注解上面完成了初始化和销毁的方法.
三 .实现接口完成
[1]初始化 实现InitializingBean接口
[2]销毁实现 DisposableBean接口
这里不做演示,因为侵入性的方式我们不喜欢用的.
四 .使用JSR标准注解帮助实现
其实这个是比较优雅的一种做法了.
@PostConstruct
@PreDestroy
前者表示在创建之后执行,后者表示在容器销毁执行.