@PostConstruct和@PreDestroy同样位于java.annotation包下,也是来自JavaEE规范的两个Annotation,Spring直接借鉴了它们,用于定制Spring容器中Bean的生命周期行为。
@PostConstruct和@PreDestroy大致相当于<bean.../>元素的 init-method 属性和 destroy-method 属性指定的方法:
@Component
public class Chinese implements Person {
@Resource(name="steelAxe")
private Axe axe;
@Override
public void useAxe() {
System.out.println(axe.chop());
}
@PostConstruct
public void init(){
System.out.println("正在执行初始化的init方法...");
}
@PreDestroy
public void close(){
System.out.println("正在执行销毁之前的close方法...");
}
}