【Spring源码解析】生命周期-InitializingBean和DisposableBean

实现

  1. 定义bean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Component
public class Cat implements InitializingBean, DisposableBean {
public Cat() {
System.out.println("cat constructor...");
}

@Override
public void destroy() throws Exception {
System.out.println("cat destroy...");
}

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("cat init...");
}
}
  1. bean注入
1
2
3
4
5
6
7
8
9
@ComponentScan("cn.idea360.bean")
@Configuration
public class BeanConfigOfLifeCycle {

@Bean(initMethod = "init", destroyMethod = "destroy")
public Car car() {
return new Car();
}
}
  1. 测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* cat constructor...
* cat init...
* car constructor...
* car init...
* 容器创建完成
* car destory...
* cat destroy...
*/
@Test
public void test07() {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfigOfLifeCycle.class);
System.out.println("容器创建完成");

// 关闭容器
applicationContext.close();
}

最后

本篇到此结束,欢迎大家关注公众号【当我遇上你】。