1. 需求
- 如何指定bean的特定的初始化init以及特定的destroy方法呢?
2. 结论
- 通过实现InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法;
- 通过 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法(这种是xml方式)
- 在指定方法上加上@PostConstruct或@PreDestroy注解来制定该方法是在初始化之后还是销毁之前调用(注解方式)
3. 使用
- xml方式直接配置即可,无难度,直接跳过。
1. 使用InitializingBean接口
-
InitializingBean接口中有个afterPropertiesSet方法,意思:在属性被设置之后执行
-
代码:
bean A@Component public class A implements InitializingBean { private String name; public A() { System.out.println("A的constructor........"); } @Override public String toString() { return "A{" + "name='" + name + '\'' + '}'; } @Override public void afterPropertiesSet() throws Exception { System.out.println("afterPropertiesSet:执行"); this.name = "A"; System.out.println("afterPropertiesSet:执行完成"); } }
测试代码:
public class Test { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.jin.king.BeanPostProcessorTest"); A a = context.getBean("a", A.class); System.out.println("getBean之后:" + a); } }
2. @PostConstruct注解指定init方法
@Component
public class A {
private String name;
public A() {
System.out.println("A的constructor........");
}
@Override
public String toString() {
return "A{" +
"name='" + name + '\'' +
'}';
}
@PostConstruct // 指定bean的init方法
public void init(){
System.out.println("----------init---------");
System.out.println(this);
this.name = "A";
System.out.println("----------init-finish---------");
}
}
3. 两者都使用了情况
-
如果有的人无意中两者都一起使用了,则注意执行的优先级,@PostConstruct注解的代码执行 优先于 afterPropertiesSet()方法
@Component public class A implements InitializingBean{ private String name; public A() { System.out.println("A的constructor........"); } @Override public String toString() { return "A{" + "name='" + name + '\'' + '}'; } @PostConstruct // 指定bean的init方法 public void init(){ System.out.println("----------@PostConstruct---------"); this.name = "A"; System.out.println("----------@PostConstruct-finish--: " + this); } @Override public void afterPropertiesSet() throws Exception { System.out.println("afterPropertiesSet:执行"); this.name = "AA"; System.out.println("afterPropertiesSet:执行完成: " + this); } }