Bean管理-生命周期管理

七步生命周期及演示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

初始化、销毁方法

指定初始化和销毁方法的方式:

  • 方式一:在类中写好initmethod和destroymethod,我们可以通过@Bean(initMethod = “init”,destroyMethod = “destroy”)来指定初始化方法和销毁方法
  • 方式二:待创建类继承并实现实现InitializingBean接口(定义初始化逻辑) DisposableBean接口(定义销毁逻辑)
  • 方式三: 可以使用JSR250规范里面定义的两个注解:
    @PostConstruct :在bean创建完成并且属性赋值完成,来执行初始化方法
    @PreDestroy :在容器销毁bean之前通知我们来进行清理工作

方式一

/**
* bean的生命周期:bean的创建->初始化->销毁的过程
* 容器管理bean的生命周期:
* 我们可以自定义初始化方法和销毁的方法:容器在bean进行到当前的生命周期的时候,来调用我们自定义的初始化方法和销毁方法
* 构造(对象创建):
*      单实例:在容器启动的时候创建对象
*      多实例:在每次获取的时候来创建对象
* 初始化方法:
*      对象创建完成,并赋值好,调用初始化方法
* 销毁方法:
*      单实例的bean:在容器关闭的时候进行销毁
*      多实例的bean:容器不会管理这个bean,容器不会调用销毁的方法
*
* 1)指定初始化方法和销毁方法;
*          -我们可以通过@Bean(initMethod = "init",destroyMethod = "destroy")来指定初始化方法和销毁方法
*          相当于xml配置文件bean标签里面的 init-method="" 和 destroy-method="" 属性
*          -通过bean实现InitializingBean(定义初始化逻辑)  DisposableBean(定义销毁逻辑);
*          -可以使用JSR250规范里面定义的两个注解:
             @PostConstruct :在bean创建完成并且属性赋值完成,来执行初始化方法
             @PreDestroy :在容器销毁bean之前通知我们来进行清理工作
*/
@Configuration
public class MainConfigOfLifeCycle {


    @Bean(initMethod = "init",destroyMethod = "destroy")
    public Car car() {
        return new Car();
    }
}

方式二

public interface InitializingBean {


    /**
     * Invoked by a BeanFactory after it has set all bean properties supplied
     * (and satisfied BeanFactoryAware and ApplicationContextAware).
     * <p>This method allows the bean instance to perform initialization only
     * possible when all bean properties have been set and to throw an
     * exception in the event of misconfiguration.
     * @throws Exception in the event of misconfiguration (such
     * as failure to set an essential property) or if initialization fails.
     */
    void afterPropertiesSet() throws Exception;


}
定义初始化方法
public interface DisposableBean {


    /**
     * Invoked by a BeanFactory on destruction of a singleton.
     * @throws Exception in case of shutdown errors.
     * Exceptions will get logged but not rethrown to allow
     * other beans to release their resources too.
     */
    void destroy() throws Exception;


}
定义销毁方法
@Component
public class Cat implements InitializingBean, DisposableBean {
    public Cat() {
        System.out.println("Cat...Contrustor...");
    }


    @Override
    public void destroy() throws Exception {
        System.out.println("Cat...destroy...");
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Cat...afterPropertiesSet...");
    }
}

带创建的bean继承并实现上述接口
/**
 * bean的生命周期:bean的创建->初始化->销毁的过程
 * 容器管理bean的生命周期:
 * 我们可以自定义初始化方法和销毁的方法:容器在bean进行到当前的生命周期的时候,来调用我们自定义的初始化方法和销毁方法
 * 构造(对象创建):
 *      单实例:在容器启动的时候创建对象
 *      多实例:在每次获取的时候来创建对象
 * 初始化方法:
 *      对象创建完成,并赋值好,调用初始化方法
 * 销毁方法:
 *      单实例的bean:在容器关闭的时候进行销毁
 *      多实例的bean:容器不会管理这个bean,容器不会调用销毁的方法
 *
 * 1)指定初始化方法和销毁方法;
 *          -我们可以通过@Bean(initMethod = "init",destroyMethod = "destroy")来指定初始化方法和销毁方法
 *          相当于xml配置文件bean标签里面的 init-method="" 和 destroy-method="" 属性
 * 2)通过bean实现InitializingBean(定义初始化逻辑)
 *               DisposableBean(定义销毁逻辑);
 *
 *
 */
@Configuration
@ComponentScan("com.ldc.bean")
public class MainConfigOfLifeCycle {

    @Bean
    public Cat cat() {
        return new Cat();
    }
}

方式三:

@PostConstruct:在bean创建完成并且属性赋值完成,要执行的初始化方法

@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PostConstruct {
}

@PreDestroy:在容器销毁bean之前通知我们来进行清理工作,即要执行的销毁方法

@Documented
@Retention (RUNTIME)
@Target(METHOD)
public @interface PreDestroy {
}
@Component
public class Dog {
    public Dog() {
        System.out.println("Dog...Contructor...");
    }


    //在对象创建并赋值之后调用
    @PostConstruct
    public void init() {
        System.out.println("Dog...@PostConstruct...");
    }


    //在对象创建并赋值之后调用
    @PreDestroy
    public void destroy() {
        System.out.println("Dog...@PreDestroy...");
    }
}

后置处理器

一句话理解:对象创建完成之后在初始化方法之前和之后运行的方法。

BeanPostProcessor接口:bean的后置处理器,在bean初始化前后做一些处理工作,这个接口有两个方法:

  • postProcessBeforeInitialization:在初始化之前工作
  • postProcessAfterInitialization:在初始化之后工作

接口源码

public interface BeanPostProcessor {


    /**
     * Apply this BeanPostProcessor to the given new bean instance <i>before</i> any bean
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
     * or a custom init-method). The bean will already be populated with property values.
     * The returned bean instance may be a wrapper around the original.
     * @param bean the new bean instance
     * @param beanName the name of the bean
     * @return the bean instance to use, either the original or a wrapped one;
     * if {@code null}, no subsequent BeanPostProcessors will be invoked
     * @throws org.springframework.beans.BeansException in case of errors
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
     */
    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;


    /**
     * Apply this BeanPostProcessor to the given new bean instance <i>after</i> any bean
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}
     * or a custom init-method). The bean will already be populated with property values.
     * The returned bean instance may be a wrapper around the original.
     * <p>In case of a FactoryBean, this callback will be invoked for both the FactoryBean
     * instance and the objects created by the FactoryBean (as of Spring 2.0). The
     * post-processor can decide whether to apply to either the FactoryBean or created
     * objects or both through corresponding {@code bean instanceof FactoryBean} checks.
     * <p>This callback will also be invoked after a short-circuiting triggered by a
     * {@link InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation} method,
     * in contrast to all other BeanPostProcessor callbacks.
     * @param bean the new bean instance
     * @param beanName the name of the bean
     * @return the bean instance to use, either the original or a wrapped one;
     * if {@code null}, no subsequent BeanPostProcessors will be invoked
     * @throws org.springframework.beans.BeansException in case of errors
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet
     * @see org.springframework.beans.factory.FactoryBean
     */
    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;


}

我们来写一个类并且实现这个后置处理器接口 BeanPostProcessor :

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization..."+beanName+"=>"+bean);
        return bean;
    }


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization..."+beanName+"=>"+bean);
        return bean;
    }
}
/**
* bean的生命周期:bean的创建->初始化->销毁的过程
* 容器管理bean的生命周期:
* 我们可以自定义初始化方法和销毁的方法:容器在bean进行到当前的生命周期的时候,来调用我们自定义的初始化方法和销毁方法
* 构造(对象创建):
*      单实例:在容器启动的时候创建对象
*      多实例:在每次获取的时候来创建对象
* 初始化方法:
*      对象创建完成,并赋值好,调用初始化方法
* 销毁方法:
*      单实例的bean:在容器关闭的时候进行销毁
*      多实例的bean:容器不会管理这个bean,容器不会调用销毁的方法
*
* 1)指定初始化方法和销毁方法;
*          -我们可以通过@Bean(initMethod = "init",destroyMethod = "destroy")来指定初始化方法和销毁方法
*          相当于xml配置文件bean标签里面的 init-method="" 和 destroy-method="" 属性
* 2)通过bean实现InitializingBean(定义初始化逻辑)
*               DisposableBean(定义销毁逻辑);
*
* 3)可以使用JSR250规范里面定义的两个注解:
*      @PostConstruct :在bean创建完成并且属性赋值完成,来执行初始化方法
*      @PreDestroy :在容器销毁bean之前通知我们来进行清理工作
* 4)BeanPostProcessor接口:bean的后置处理器
* 在bean初始化前后做一些处理工作,这个接口有两个方法:
*      - postProcessBeforeInitialization:在初始化之前工作
*      - postProcessAfterInitialization:在初始化之后工作
*/
@Configuration
@ComponentScan("com.ldc.bean")
public class MainConfigOfLifeCycle {


    @Bean(initMethod = "init",destroyMethod = "destroy")
    public Car car() {
        return new Car();
    }
}

总结

/**
* bean的生命周期:
*        bean创建---属性赋值---前置处理器---初始化---后置处理器----销毁的过程
* 容器管理bean的生命周期;
* 我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法
*
* 构造(对象创建)
*        单实例:在容器启动的时候创建对象
*        多实例:在每次获取的时候创建对象
*
*对象创建完成,并赋值好:
* BeanPostProcessor.postProcessBeforeInitialization:此时是把Bean实例传递给前置处理器方法
* 初始化:
*        调用初始化方法。。。
* BeanPostProcessor.postProcessAfterInitialization:此时是把Bean实例传递给后置处理器放过发
* 销毁:
*        单实例:容器关闭的时候
*        多实例:容器不会管理这个bean;容器不会调用销毁方法;
*
*
* 遍历得到容器中所有的BeanPostProcessor;挨个执行beforeInitialization,
* 一但返回null,跳出for循环,不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization
*
* BeanPostProcessor原理
* bean创建,然后
* populateBean(beanName, mbd, instanceWrapper);给bean进行属性赋值
* initializeBean
* {
* applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
* invokeInitMethods(beanName, wrappedBean, mbd);执行自定义初始化
* applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
*}
*
*
* Bean初始化和销毁方法的实现:
* 1)、指定初始化和销毁方法;
*        通过@Bean指定init-method和destroy-method;
* 2)、通过让Bean实现InitializingBean接口(定义初始化逻辑),
*              DisposableBean接口(定义销毁逻辑);
* 3)、可以使用JSR250;标注在bean中的方法上
*        @PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
*        @PreDestroy:在容器销毁bean之前通知我们进行清理工作
* 4)、BeanPostProcessor【interface】:bean的后置处理器;   很重要
*        在bean初始化前后进行一些处理工作;
*        postProcessBeforeInitialization:在初始化方法之前工作
*        postProcessAfterInitialization:在初始化之后工作
*
* Spring底层对 BeanPostProcessor 的使用;
*        bean赋值,注入其他组件,@Autowired,生命周期注解功能,@Async,xxx BeanPostProcessor;
*
*
* 总的流程:
* 创建对象
* 对象属性赋值
* postProcessBeforeInitialization
* 自定义初始化方法
* postProcessAfterInitialization
*
* 对象销毁
* 自定义销毁方法
*
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值