bean的初始化和销毁实际是spring本身的特性,这里因为基于spring boot的,所以这里只关注通过annotation来实现的方式;
首先定义配置类:
@Configuration
public class DemoBeanConfiguration {
@Bean
public DemoBean getBean() {
return new DemoBean();
}
}
----------
public class DemoBean {
private void init() {
System.out.println("init");
}
private void destroy() {
System.out.println("destroy");
}
}
然后在@Bean中定义init和destroy方法
@Bean(initMethod = "init", destroyMethod = "destroy")
public DemoBean getBean() {
return new DemoBean();
}
运行main
方法:
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(SpringBootDemoApplication.class);
DemoBean bean = run.getBean(DemoBean.class);
run.close();
}
控制台分别打印init和destroy