美文网首页
不完全spring学习-6Bean生命周期

不完全spring学习-6Bean生命周期

作者: 闲杂人等 | 来源:发表于2020-05-10 15:54 被阅读0次

    四种方法

    1. @Bean(initMethod="init-mathod-name",destroy="destroy-method-name")
    2. @PostConstruct和@PreDestroy
    3. 实现InitializingBean,DisposableBean
    4. 实现BeanPostProcessor

    @Bean(initMethod="init-mathod-name",destroy="destroy-method-name")

    //bean
    public class ABean{
        public void init() {
            //dosomthing
        }
       public void destroy() {
            //do destroy
       }
    }
    // config文件
    @Configuration
    public class Config {
        @Bean(initMethod="init",destroy=”destroy")
        public ABean aBean() {
            return new ABean();
       }
    }
    
    

    @PostConstruct和@PreDestroy

    @Component
    public class AComponent {
        @PostConstructor
        public void postConstructor () {
            // do something
       }
       @PreDestroy
       public void preDestroy() {
            //do some thing
       }
    }
    

    实现InitializingBean,DisposableBean

    @Component
    public class AComponent  implements InitializingBean,DisposableBean{
        @Override
        public void destroy() throws Exception {
            //do something
        }
       @Override
        public void afterPropertiesSet() throws Exception {
             //do something
        }
    }
    

    实现BeanPostProcessor

    @Component
    public class AComponent  DisposableBean{
        @Override
        public Object postProcessAfterInitialization(Object bean,String beanName) throws BeansException {
            //do something
        }
        @Override
        public Object postProcessBeforeInitialization(Object bean,String beanName) throws BeansException {
            //do something
        }
    }
    

    Spring底层对BeanPostProcessor的应用

    可结合ApplicationAware接口和BeanPostProcessor,处理各类注解

    相关文章

      网友评论

          本文标题:不完全spring学习-6Bean生命周期

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