(二)Bean的生命周期

Bean的生命周期

Bean的初始化和销毁

一、使用@Bean注解的初始化和销毁属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 在dog实例中指定init和destroy方法
public class Dog {

public void init(){
System.out.println("instance dog execute init method.....");
}

public void destroy(){
System.out.println("instance dog execute destroy method.....");
}
}

// 声明bean的时候指定 initMethod = "init",destroyMethod = "destroy"
@Configurable
public class LifeCycleConfig {
@Bean(initMethod = "init",destroyMethod = "destroy")
public Dog dog(){
System.out.println("begin create dog");
return new Dog();
}
}
// 执行测试
@Test
public void LifeCycleTest(){
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
System.out.println("instance has created !!!");
// Dog dog = (Dog) applicationContext.getBean("dog");
((AnnotationConfigApplicationContext) applicationContext).close();
System.out.println("context has closed !!!");
}

// 测试结果:
// begin create dog
// instance dog execute init method.....
// instance has created !!!
// instance dog execute destroy method.....
// context has closed !!!

从测试结果来看当创建对象时,通过 initMethod,destroyMethod指定初始化和销毁方法时可行的。

init方法在对象创建后执行。destroy容器销毁前执行.

二、继承 InitializingBean 和 DisposableBean 接口

方法同上,不过需要对象类实现这两个接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Cat implements InitializingBean, DisposableBean {

// 接口中的destroy 方法,执行销毁bean
public void destroy() throws Exception {
System.out.println("instance cat execute destroy method.....");
}
// 接口中的afterPropertiesSet方法,用来创建bean后的初始化
public void afterPropertiesSet() throws Exception {
System.out.println("instance cat execute init method.....");
}
}

// 不需要在bean注解中指定相关方法
@Bean
public Cat cat(){
System.out.println("begin create cat");
return new Cat();
}

//用同样的测试程序测试得到的结果如下:
// begin create cat
// instance dog execute init method.....
// instance has created !!!
// instance dog execute destroy method.....
// context has closed !!!

三、使用JSR标准注解 @PostConstruce 和 @PreDestroy

1
2
3
4
5
6
7
8
9
10
11
12
public class Bug {

@PostConstruct
public void init(){
System.out.println("instance Bug execute init method.....");
}

@PreDestroy
public void destroy(){
System.out.println("instance Bug execute destroy method.....");
}
}

四、BeanPostProcessor自定义初始化前后方法

先自定义一个 MyBeanPostProcessor ,并将它放到容器中,在启动后,每次生成bean时,都会执行下面的 postProcessBeforeInitializationpostProcessAfterInitializationde 前置方法和后置方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
// 根据BeanName和bean可以获取bean的类信息接下来就可以进行筛选,在初始化前进行相关操作
System.out.println(beanName);
return null;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName);
// 同理初始化后
return null;
}
}



-------------本文结束感谢您的阅读-------------