学习目标:
主程序类
- @SpringBootApplication
- public class A07Application_1 {
- public static void main(String[] args) {
- ConfigurableApplicationContext context = SpringApplication.run(A07Application_1.class, args);
- context.close();
- }
-
- @Bean(initMethod = "init3")
- public Bean1 bean1() {
- return new Bean1();
- }
-
- @Bean(destroyMethod = "destroy3")
- public Bean2 bean2() {
- return new Bean2();
- }
- }
Bean1类
- public class Bean1 implements InitializingBean {
- private static final Logger log = LoggerFactory.getLogger(Bean1.class);
-
- @PostConstruct
- public void init1() {
- log.debug("初始化1");
- }
-
- @Override
- public void afterPropertiesSet() throws Exception {
- log.debug("初始化2");
- }
-
- public void init3() {
- log.debug("初始化3");
- }
- }
Bean2类
- public class Bean2 implements DisposableBean {
- private static final Logger log = LoggerFactory.getLogger(Bean2.class);
-
- @PreDestroy
- public void destroy1() {
- log.debug("销毁1");
- }
-
- @Override
- public void destroy() throws Exception {
- log.debug("销毁2");
- }
-
- public void destroy3() {
- log.debug("销毁3");
- }
- }
结果:
- [main] com.itheima.a07.Bean1 - 初始化1
- [main] com.itheima.a07.Bean1 - 初始化2
- [main] com.itheima.a07.Bean1 - 初始化3
- [main] com.itheima.a07.Bean2 - 销毁1
- [main] com.itheima.a07.Bean2 - 销毁2
- [main] com.itheima.a07.Bean2 - 销毁3
总结:
Spring 提供了多种初始化手段, @PostConstruct,@Bean(initMethod) 以及实现 InitializingBean 接口来进行初始化,如果同一个 bean 用了以上手段声明了 3 个初始化方法,那么它们的执行顺序是:
@PostConstruct 标注的初始化方法
InitializingBean 接口的初始化方法
@Bean(initMethod) 指定的初始化方法
与初始化类似,Spring 也提供了多种销毁手段,执行顺序为
@PreDestroy 标注的销毁方法
DisposableBean 接口的销毁方法
@Bean(destroyMethod) 指定的销毁方法
- public class A07Application_2 {
- public static void main(String[] args) {
- DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
- beanFactory.registerBeanDefinition(
- "myBean",
- BeanDefinitionBuilder.genericBeanDefinition(MyBean.class)
- .setDestroyMethodName("destroy")
- .getBeanDefinition()
- );
-
- System.out.println(beanFactory.getBean(MyBean.class));
- beanFactory.destroySingletons(); // 销毁之后, 仍可创建新的单例
- System.out.println(beanFactory.getBean(MyBean.class));
-
- }
-
- static class MyBean {
- public MyBean() {
- System.out.println("MyBean()");
- }
-
- public void destroy() {
- System.out.println("destroy()");
- }
- }
- }
结果:
- MyBean()
- com.itheima.a07.A07Application_2$MyBean@7b98f307
- destroy()
- MyBean()
- com.itheima.a07.A07Application_2$MyBean@41d477ed