这篇文章主要介绍了Spring初始化与销毁的执行顺序是什么的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Spring初始化与销毁的执行顺序是什么文章都会有所收获,下面我们一起来看看吧。
演示 - 初始化销毁顺序
/* 初始化和销毁的执行顺序 */ @SpringBootApplication public class A07_1 { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(A07_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"); } }
输出结果: