初始化和销毁

初始化方法

  1. @PostConstruct
  1. implements InitializingBean 覆盖afterPropertiesSet() 方法
  1. @Bean(initMethod = "初始化方法")
如果同时存在按照上述顺序执行
 
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"); } }
 
[DEBUG] 11:02:30.164 [main] com.onethink.a07.Bean1 - 初始化1 [DEBUG] 11:02:30.164 [main] com.onethink.a07.Bean1 - 初始化2 [DEBUG] 11:02:30.164 [main] com.onethink.a07.Bean1 - 初始化3

Aware 方法的扩展

aware方法会在 @PostConstruct 之前执行
 
public class Bean1 implements InitializingBean, BeanNameAware, ApplicationContextAware { 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"); } @Override public void setBeanName(String name) { log.debug("初始化4"); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { log.debug("初始化5"); } }
[DEBUG] 11:13:52.334 [main] com.onethink.a07.Bean1 - 初始化4 [DEBUG] 11:13:52.334 [main] com.onethink.a07.Bean1 - 初始化5 [DEBUG] 11:13:52.334 [main] com.onethink.a07.Bean1 - 初始化1 [DEBUG] 11:13:52.334 [main] com.onethink.a07.Bean1 - 初始化2 [DEBUG] 11:13:52.334 [main] com.onethink.a07.Bean1 - 初始化3

销毁方法

  1. @PreDestroy
  1. implements DisposableBean 重写destroy()
  1. @Bean(destroyMethod = "destroy3")
 
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"); } }
public class A07_1 { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(A07_1.class, args); context.close(); } @Bean(destroyMethod = "destroy3") public Bean2 bean2() { return new Bean2(); } }
 
[DEBUG] 11:02:30.631 [main] com.onethink.a07.Bean2 - 销毁1 [DEBUG] 11:02:30.631 [main] com.onethink.a07.Bean2 - 销毁2 [DEBUG] 11:02:30.631 [main] com.onethink.a07.Bean2 - 销毁3