Spring注解驱动开发 第九节 使用@PostConstruct与@PreDestroy自定义初始化与销毁方法
上一节,我们采用实现InitializingBean与DisposableBean接口来自定义初始化与销毁方法,现在我们使用第三种方式自定义。
@Component
public class Dog {
public Dog(){
System.out.println("Dog 默认构造器加载了...");
}
@PostConstruct
public void init(){
System.out.println("Dog @PostConstruct ...");
}
@PreDestroy
public void destory(){
System.out.println("Dog destory ...");
}
}
@PostConstruct注解表示bean被创建,属性被赋值后进行调用初始化操作。@PreDestroy注释表示spring容器关闭前对bean的逻辑操作。
打印结果:
四月 23, 2019 2:54:06 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f410acf: startup date [Tue Apr 23 14:54:06 GMT+08:00 2019]; root of context hierarchy
black构造器被调用了....
black afterPropertiesSet ...
Dog 默认构造器加载了...
Dog @PostConstruct ...
Blue被加载到spring容器中了...
Blue init...
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig4
black
dog
blue
Blue destory...
Dog destory ...
black destroy ...
四月 23, 2019 2:54:07 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f410acf: startup date [Tue Apr 23 14:54:06 GMT+08:00 2019]; root of context hierarchy
Process finished with exit code 0
可以看到Dog首先被spring调用构造器创建对象,然后spring调用了我们自定义的初始化方法,当容器销毁前,调用我们自定义的销毁方法。这里需要注意这种方法同时也是JSR250规范