三、Spring Bean

文章详细阐述了Spring框架中Bean的生命周期,包括单例和多例Bean的创建与销毁。介绍了initMethod和destroyMethod、@PostConstruct和@PreDestroy注解的使用,以及InitializingBean和DisposableBean接口在生命周期中的角色。此外,还提到了BeanPostProcessor和InstantiationAwareBeanPostProcessor接口在Bean处理过程中的作用,以及如何通过FactoryBean接口注册组件。
摘要由CSDN通过智能技术生成

一、Bean 的生命周期


1. 什么是 Bean 的生命周期?

  1. Bean 的 创建 > 初始化 > 销毁。
  2. 由容器管理 Bean 的生命周期,可以指定 Bean 的 初始化 和 销毁方法。

  • 针对 单例 Bean 的话
  1. 容器启动的时候,Bean 对象就创建了。
  2. 容器销毁的时候,也会调用 Bean 销毁方法。
  • 针对 多例 Bean 的话
  1. 容器启动的时候,Bean 是不会被创建的,而是在获取 Bean 的时候被创建。
  2. Bean 销毁不受 IOC 容器的管理。

2. initMethod 和 destroyMethod

  • initMethod 构造后。
  • destroyMethod 销毁前 (多例时不会调用)。
@Scope("prototype")
@Bean(initMethod = "init", destroyMethod = "destroy")
public Qs qs() {
    return new Qs();
}

3. @PostConstruct 和 @PreDestroy

  • 通过 JSR250 规范,提供的注解。
  1. @PostConstruct 构造后。
  2. @PreDestroy 销毁前 (多例时不会调用)。
/**
 * @author wy
 * describe
 */
@Component
public class QsHome {

    /**
     * `@PostConstruct`构造后。
     */
    @PostConstruct
    public void init() {
        System.out.printf("`%s`init", this.getClass().getName()).println();
    }


    /**
     * `@PreDestroy`销毁前(多例时不会调用)。
     */
    @PreDestroy
    public void destroy() {
        System.out.printf("`%s`destroy", this.getClass().getName()).println();
    }
}

4. InitializingBean 初始化 Bean

/**
 * @author wy
 * describe 初始化`Bean`。
 * `InitializingBean.afterPropertiesSet`。
 */
@Component
public class MyInitializingBean implements InitializingBean {

	/**
     * `@PostConstruct`构造后。
     */
    @PostConstruct
    public void init() {
        System.out.printf("`%s`init", this.getClass().getName()).println();
    }

    /**
     * `@PostConstruct`后,`setXX`前。
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.printf("`%s`afterPropertiesSet", this.getClass().getName()).println();
        // 此处可设置`Bean属性`。
    }
}

5. DisposableBean 销毁 Bean

/**
 * @author wy
 * describe 销毁`Bean`。
 * `DisposableBean.destroy()`。
 */
@Component
public class MyDisposableBean implements DisposableBean {

    /**
     * `@PreDestroy`销毁前(多例时不会调用)。
     */
    @PreDestroy
    public void preDestroy() {
        System.out.printf("`%s`preDestroy", this.getClass().getName()).println();
    }

    /**
     * 销毁前,`@PreDestroy`后(多例时不会调用)。
     */
    @Override
    public void destroy() throws Exception {
        System.out.printf("`%s`destroy", this.getClass().getName()).println();
    }
}

6. BeanPostProcessor Bean 的后置处理器

/**
 * @author wy
 * describe `Bean`的后置处理器。
 * 用于修改`Bean属性`。
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    /**
     * `@PostConstruct`构造后。
     */
    @PostConstruct
    public void init() {
        System.out.printf("`%s`init", this.getClass().getName()).println();
    }

    /**
     * 初始化前(`@PostConstruct`后)。
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.printf("`%s`postProcessBeforeInitialization,beanName = %s", this.getClass().getName(), beanName).println();
        // 此处可设置`Bean属性`。
        return bean;
    }

    /**
     * 初始化后。
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.printf("`%s`postProcessAfterInitialization,beanName = %s", this.getClass().getName(), beanName).println();
        // 此处可设置`Bean属性`。
        return bean;
    }
}

7. InstantiationAwareBeanPostProcessor 实例化 Bean 的后置处理器

/**
 * @author wy
 * describe `实例化Bean`的后置处理器。
 */
@Component
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    /**
     * `@PostConstruct`构造后。
     */
    @PostConstruct
    public void init() {
        System.out.printf("`%s`init", this.getClass().getName()).println();
    }

    /**
     * 1. 实例化前。
     */
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        System.out.printf("`%s`postProcessBeforeInstantiation,beanName = %s", this.getClass().getName(), beanName).println();
        return null;
    }

    /**
     * 2. 实例化后。
     */
    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        System.out.printf("`%s`postProcessAfterInstantiation,beanName = %s", this.getClass().getName(), beanName).println();
        return false;
    }

    /**
     * 属性值。
     */
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
        System.out.printf("`%s`postProcessPropertyValues,beanName = %s", this.getClass().getName(), beanName).println();
        return pvs;
    }

    /**
     * 3. 初始化前。
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.printf("`%s`postProcessBeforeInitialization,beanName = %s", this.getClass().getName(), beanName).println();
        return bean;
    }

    /**
     * 4. 初始化后。
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.printf("`%s`postProcessAfterInitialization,beanName = %s", this.getClass().getName(), beanName).println();
        return bean;
    }
}

二、注册 Bean


1. 四种注解方式,往 IOC 容器中添加组件

  1. @CompentScan + @Compent (@Controller、@Service、@Repository) 扫描 Bean,适用于自己写的组件可以通过扫描来加载到容器中。
  2. @Bean 适用于导入第三方组件的类。
  3. @Import 导入Bean,导入 组件的ID 为 全类名路径。
  4. @ImportResource 导入 Xml 配置文件。

2. FactoryBean 接口,往容器中注册组件

/**
 * @author wy
 * describe `FactoryBean`接口,往容器中注册组件(懒加载)。
 * 用于设置大量属性。
 */
@Data
public class CarFactoryBean implements FactoryBean<Car> {

    public CarFactoryBean() {
        System.out.printf("`%s`无参构造", this.getClass().getName()).println();
    }

    /**
     * 返回`Bean对象`。
     */
    @Override
    public Car getObject() throws Exception {
        return new Car();
    }

    /**
     * 返回`Bean类型`。
     */
    @Override
    public Class<?> getObjectType() {
        return Car.class;
    }

    /**
     * 是否为单例。
     */
    @Override
    public boolean isSingleton() {
        return false;
    }

}

/**
 * @author wy
 * describe 
 * 数据库驱动类,设置`url`。
 */
@Data
public class DriverFactoryBean implements FactoryBean {

    private String jdbcUrl;

    @Override
    public Object getObject() throws Exception {
        return DriverManager.getDriver(jdbcUrl);
    }

    @Override
    public Class<?> getObjectType() {
        return java.sql.Driver.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

骑士梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值