详情请阅读:Spring编程常见错误50例

创建一个配置类 BeanConfiguration(标记@Configuration)来创建一堆 Bean 时,如果Bean中有 close()或者 shutdown() 方法,当 AnnotationConfigApplicationContext 的 close 方法被调用时,即当 Spring 容器被销毁时,最终会自动调用依次调用其中的 close()或者 shutdown() 方法

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. @Configuration
  4. public class BeanConfiguration {
  5. @Bean
  6. public LightService getTransmission(){
  7. return new LightService();
  8. }
  9. }
  10. @Service
  11. public class LightService {
  12. public void start() {
  13. System.out.println("turn on all lights");
  14. }
  15. public void shutdown() {
  16. System.out.println("turn off all lights");
  17. }
  18. public void check() {
  19. System.out.println("check all lights");
  20. }
  21. }

如何避免

  1. 不要使用关键字 shutdown 或 close
  2. 使用 @Bean(destroyMethod="")