Spring Bean的生命周期学习

1、Spring Bean的整个生命周期图:

 

2、@PostConstructor@PreDestroy注解:

1 @PostConstruct
2 public void afterConstructor() {
3     System.out.println("after constructor..............");
4 }
5 
6 @PreDestroy
7 public void beforeDestroy() {
8     System.out.println("before destroy..............");
9 }

3、InitializingBean, DisposableBean 接口:

 1 public class SpringLifeCycleService implements InitializingBean,DisposableBean{
 2     
 3     @Override
 4     public void afterPropertiesSet() throws Exception {
 5         System.out.println("SpringLifeCycleService start");
 6     }
 7 
 8     @Override
 9     public void destroy() throws Exception {
10         System.out.println("SpringLifeCycleService destroy");
11     }
12 }

4、指定init-method方法:

 

 1 public class SpringLifeCycleService implements InitializingBean,DisposableBean{
 2     
 3     @Override
 4     public void start() {
 5         System.out.println("starting..........");
 6     }
 7 
 8     @Override
 9     public void stop() {
10         System.out.println("stopping...............");
11     }
12 }

 

并且在SpringMVC配置文件中添加:

<bean class="*.*.SpringLifeCycleService" init-method="start" destroy-method="stop"></bean>

5、BeanPostProcessor 接口:

 1 public class MyTestImpl implements BeanPostProcessor {
 2 
 3     @Override
 4     public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
 5         System.out.println("BeanPostProcessor before init");
 6         return o;
 7     }
 8 
 9     @Override
10     public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
11         System.out.println("BeanPostProcessor after init");
12         return o;
13     }
14 }

 

posted on 2019-10-15 21:22  小夏coding  阅读(181)  评论(0编辑  收藏  举报

导航