Spring 提供了多种初始化手段,除了 @PostConstruct,@Bean(initMethod) 之外,还可以实现 InitializingBean 接口来进行初始化,如果同一个 bean 用了以上手段声明了 3 个初始化方法,那么它们的执行顺序是
package com.mangoubiubiu.show.a07; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.InitializingBean; import javax.annotation.PostConstruct; @Slf4j public class Bean1 implements InitializingBean { @PostConstruct public void init(){ log.info("PostConstruct init 初始化1"); } public void init2(){ log.info("Bean init init2 初始化2"); } @Override public void afterPropertiesSet() throws Exception { log.info("InitializingBean 初始化2"); } }
package com.mangoubiubiu.show.a07; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; @SpringBootApplication public class A07Application { public static void main(String[] args) { ConfigurableApplicationContext run = SpringApplication.run(A07Application.class); run.close(); } @Bean(initMethod = "init2") public Bean1 bean1(){ return new Bean1(); } }
与初始化类似,Spring 也提供了多种销毁手段,执行顺序为
package com.mangoubiubiu.show.a07; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; @Slf4j public class Bean2 implements DisposableBean { @PreDestroy public void destroy1(){ log.info("PreDestroy 销毁"); } public void destroy2(){ log.info("Bean 初始化1"); } @Override public void destroy() throws Exception { log.info("DisposableBean 销毁2"); } }
package com.mangoubiubiu.show.a07; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; @SpringBootApplication public class A07Application { public static void main(String[] args) { ConfigurableApplicationContext run = SpringApplication.run(A07Application.class); run.close(); } // @Bean(initMethod = "init2") // public Bean1 bean1(){ // return new Bean1(); // } @Bean(destroyMethod = "destroy") public Bean2 bean2(){ return new Bean2(); } }
初始化和销毁方法的执行顺序一样,先执行扩展,再执行接口方式的初始化,再执行Bean注解内方法的初始化