结论先行
可以使用JSR250规范
@PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
@PreDestroy:在容器销毁bean之前通知我们进行清理工作
bean定义
package com.ouyangxizhu.bean;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class Dog {
public Dog() {
System.out.println("dog..............constructor");
}
@PostConstruct
public void init(){
System.out.println("dog..............@PostConstruct");
}
@PreDestroy
public void destroy(){
System.out.println("dog..............@PreDestroy");
}
}
配置类
package com.ouyangxizhu.config;
import com.ouyangxizhu.bean.Dog;
import org.springframework.context.annotation.Bean;
public class MainConfigPostConstructPreDestroy {
@Bean
public Dog dog() {
return new Dog();
}
}
启动类
package com.ouyangxizhu.config;
import com.ouyangxizhu.bean.Dog;
import org.springframework.context.annotation.Bean;
public class MainConfigPostConstructPreDestroy {
@Bean
public Dog dog() {
return new Dog();
}
}
结果
八月 04, 2020 10:33:43 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@31cefde0: startup date [Tue Aug 04 22:33:43 CST 2020]; root of context hierarchy
dog..............constructor
dog..............@PostConstruct
八月 04, 2020 10:33:44 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@31cefde0: startup date [Tue Aug 04 22:33:43 CST 2020]; root of context hierarchy
dog..............@PreDestroy