bean的初始化和銷毀實(shí)際是spring本身的特性,這里因?yàn)榛趕pring boot的,所以這里只關(guān)注通過(guò)annotation來(lái)實(shí)現(xiàn)的方式;
首先定義配置類:
@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();
}
運(yùn)行main
方法:
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(SpringBootDemoApplication.class);
DemoBean bean = run.getBean(DemoBean.class);
run.close();
}
控制臺(tái)分別打印init和destroy