美文网首页SSM我爱编程
Spring自定义Bean创建与销毁方式的总结

Spring自定义Bean创建与销毁方式的总结

作者: luoyoub | 来源:发表于2018-06-21 22:52 被阅读0次

    1.注解方式

    在 bean 初始化时会经历几个阶段,首先可以使用注解 @PostConstruct, @PreDestroy 来在 bean 的创建和销毁阶段进行调用:

    @Component
    public class AnnotationBean {
        private final static Logger LOGGER = LoggerFactory.getLogger(AnnotationBean.class);
    
        @PostConstruct
        public void start(){
            LOGGER.info("AnnotationBean start");
        }
    
        @PreDestroy
        public void destroy(){
            LOGGER.info("AnnotationBean destroy");
        }
    }
    

    2.实现InitializingBean, DisposableBean接口

    @Service
    public class SpringLifeCycleService implements InitializingBean,DisposableBean{
        private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycleService.class);
        @Override
        public void afterPropertiesSet() throws Exception {
            LOGGER.info("SpringLifeCycleService start");
        }
    
        @Override
        public void destroy() throws Exception {
            LOGGER.info("SpringLifeCycleService destroy");
        }
    }
    

    3.JAVA Config方式

    @Configuration
    public class LifeCycleConfig {
    
    
        @Bean(initMethod = "start", destroyMethod = "destroy")
        public SpringLifeCycle create(){
            SpringLifeCycle springLifeCycle = new SpringLifeCycle() ;
    
            return springLifeCycle ;
        }
    }
    
    public class SpringLifeCycle{
    
        private final static Logger LOGGER = LoggerFactory.getLogger(SpringLifeCycle.class);
        public void start(){
            LOGGER.info("SpringLifeCycle start");
        }
    
    
        public void destroy(){
            LOGGER.info("SpringLifeCycle destroy");
        }
    }
    

    4. XML配置方式

    <bean class="com.crossoverjie.spring.SpringLifeCycle" init-method="start" destroy-method="destroy">
    </bean>
    

    相关文章

      网友评论

        本文标题:Spring自定义Bean创建与销毁方式的总结

        本文链接:https://www.haomeiwen.com/subject/uvhhyftx.html