Bean的初始化&销毁

86 阅读4分钟

Bean的生命周期

在传统的Java应用中,实例的生命周期很简单,使用Java关键字 new 进行对象的实例化,然后就能够使用了。一旦b实例不再被使用,则由Java自动进行垃圾回收。

相比之下,Spring管理Bean的生命周期就复杂多了,正确理解Bean 的生命周期非常重要,因为Spring对Bean的管理可扩展性非常强,下面展示了一个Bean的构造过程

image.png

  • Bean的生命周期就是bean对象的创建,赋值,初始化,销毁的过程。

我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法

构造(对象创建)

  • 单实例:在容器启动的时候创建对象
  • 多实例:在每次获取的时候创建对象

初始化,销毁

  • 初始化 : 对象创建完成,并赋值好,调用初始化方法
  • 销毁
    • 单实例:容器关闭的时候
    • 多实例:容器不会管理这个bean;容器不会调用销毁方法;

指定初始化和销毁方法

  • 通过@Bean指定init-method和destroy-method
  • 通过让Bean实现InitializingBean(定义初始化逻辑),DisposableBean(定义销毁逻辑)
  • 使用JSR250
    • @PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
    • @PreDestroy:在容器销毁bean之前通知我们进行清理工作
  • BeanPostProcessor【interface】:bean的后置处理器,在bean初始化前后进行一些处理工作;
    • postProcessBeforeInitialization:在初始化之前工作
    • postProcessAfterInitialization:在初始化之后工作

通过@Bean指定init-method和destroy-method

package com.evan.bean;

import org.springframework.stereotype.Component;

@Component
public class Car01 {

    public Car01() {
        System.out.println("car constructor ....");
    }

    public void init() {
        System.out.println("car init ......");
    }

    public void distroy() {
        System.out.println("car distroy ....");
    }
}

package com.evan.config.lifeCycle;

import com.evan.bean.Car01;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MainConfig01 {
    @Bean(initMethod = "init", destroyMethod = "distroy")
    public Car01 car() {
        return new Car01();
    }
}

package com.evan.demo.lifeCycle;

import com.evan.config.lifeCycle.MainConfig01;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainTest01 {
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig01.class);

    @Test
    public void test01() {
        System.out.println("容器创建完成。。。");
        //关闭容器
        applicationContext.close();
    }
}

car constructor ....
car init ......
容器创建完成 ....
car distroy ....

通过让Bean实现InitializingBean(定义初始化逻辑),DisposableBean(定义销毁逻辑)

package com.evan.bean;


import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class Cat implements InitializingBean, DisposableBean {

    public Cat() {
        System.out.println("cat constructor ....");
    }

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

    /**
     * 对象创建完成,并赋值好,调用初始化方法
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("cat init ....");
    }
}

@Configuration
@Import({Cat.class})
public class MainConfig01 {
    @Bean(initMethod = "init", destroyMethod = "distroy")
    public Car01 car() {
        return new Car01();
    }
}
cat constructor ....
cat init ....
car constructor ....
car init ......
容器创建完成。。。
car distroy ....
cat destroy ....

使用JSR250

  • @PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
  • @PreDestroy:在容器销毁bean之前通知我们进行清理工作
package com.evan.bean;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;


@Component
public class Dog {
    
    public Dog(){
        System.out.println("dog constructor ....");
    }

    @PostConstruct
    public void postConstruct(){
        System.out.println("dog constructor ....postConstruct....");
    }

    @PreDestroy
    public void preDestroy(){
        System.out.println("dog constructor ....preDestroy....");
    }

}

package com.evan.config.lifeCycle;

import com.evan.bean.Car01;
import com.evan.bean.Cat;
import com.evan.bean.Dog;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({Cat.class, Dog.class})
public class MainConfig01 {
    @Bean(initMethod = "init", destroyMethod = "distroy")
    public Car01 car() {
        return new Car01();
    }
}
cat constructor ....
cat init ....
dog constructor ....
dog constructor ....postConstruct....
car constructor ....
car init ......
容器创建完成。。。
car distroy ....
dog constructor ....preDestroy....
cat destroy ....

BeanPostProcessor【interface】:bean的后置处理器,在bean初始化前后进行一些处理工作;

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

源码


package org.springframework.beans.factory.config;

import org.springframework.beans.BeansException;


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;

}

postProcessBeforeInitialization: Apply this BeanPostProcessor to the given new bean instance before any bean nitialization callbacks (like InitializingBean's {@code afterPropertiesSet} or a custom init-method). The bean will already be populated with property values.

postProcessAfterInitialization:Apply this BeanPostProcessor to the given new bean instance after any bean initialization callbacks (like InitializingBean's {@code afterPropertiesSet} or a custom init-method). The bean will already be populated with property values.

和前面的不一样哟

package com.evan.config.lifeCycle;

import com.evan.bean.Car01;
import com.evan.bean.Cat;
import com.evan.bean.Dog;
import com.evan.dao.MyBeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({Cat.class, Dog.class, MyBeanPostProcessor.class})
public class MainConfig01 {
    @Bean(initMethod = "init", destroyMethod = "distroy")
    public Car01 car() {
        return new Car01();
    }
}

package com.evan.dao;

import lombok.ToString;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Service;


@Service
@ToString
public class MyBeanPostProcessor implements BeanPostProcessor {

    // 在初始化之前工作
    @Override
    public Object postProcessBeforeInitialization(Object bean, String s) throws BeansException {
        System.out.println("postProcessBeforeInitialization......" + bean.toString());
        return bean;
    }

    // 在初始化之后工作
    @Override
    public Object postProcessAfterInitialization(Object bean, String s) throws BeansException {
        System.out.println("postProcessAfterInitialization...." + bean.toString());
        return bean;
    }
}

postProcessBeforeInitialization......org.springframework.context.event.EventListenerMethodProcessor@21e360a
postProcessAfterInitialization....org.springframework.context.event.EventListenerMethodProcessor@21e360a
postProcessBeforeInitialization......org.springframework.context.event.DefaultEventListenerFactory@5ba3f27a
postProcessAfterInitialization....org.springframework.context.event.DefaultEventListenerFactory@5ba3f27a
postProcessBeforeInitialization......com.evan.config.lifeCycle.MainConfig01$$EnhancerBySpringCGLIB$$51096e26@741a8937
postProcessAfterInitialization....com.evan.config.lifeCycle.MainConfig01$$EnhancerBySpringCGLIB$$51096e26@741a8937
cat constructor ....
postProcessBeforeInitialization......com.evan.bean.Cat@306e95ec
cat init ....
postProcessAfterInitialization....com.evan.bean.Cat@306e95ec
dog constructor ....
postProcessBeforeInitialization......com.evan.bean.Dog@209da20d
dog constructor ....postConstruct....
postProcessAfterInitialization....com.evan.bean.Dog@209da20d
car constructor ....
postProcessBeforeInitialization......com.evan.bean.Car01@59505b48
car init ......
postProcessAfterInitialization....com.evan.bean.Car01@59505b48
容器创建完成。。。
car distroy ....
dog constructor ....preDestroy....
cat destroy ....