Spring Bean的生命周期

Spring Bean的生命周期

  • 2 Spring Bean的生命周期
    • 2.1 @Bean指定初始化和销毁方法
    • 2.2 InitializingBean 和 DisposableBean接口
    • 2.3 @PostConstruct 和 @PreDestroy
    • 2.4 BeanPostProcessor接口
    • 2.5 BeanPostProcessor原理
    • 2.6 BeanPostProcessor在Spring底层的使用

  

2 Spring Bean的生命周期

2.1 @Bean指定初始化和销毁方法

  bean的生命周期包括:bean创建、初始化、销毁的过程。我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用 自定义的初始化和销毁的方法。
(1)、指定初始化和销毁的方法

<bean id="person" class="domain.Person" init-method="" destroy-method="">

构造(对象创建):
  单实例,在容器启动的时候创建对象
  多实例,在每次获取的时候创建对象
初始化:
  对象创建完成、并赋值好、调用初始化方法
销毁:
  单实例在容器关闭的时候
  多实例容器不会管理整个bean,容器不会调用销毁方法
(2)测试

@Configuration
public class MainConfigLifeCycle {

    @Bean
    public Car car (){
        return new Car();
    }
}
public class Car {
    public Car() {
        System.out.println("car constructor.....");
    }
    public void init() {
        System.out.println("car init....");
    }
    public void destory () {
        System.out.println("car destory....");
    }
}
public class IocTest_LiftCycle {

    @Test
    public void test01(){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigLifeCycle.class);
        System.out.println("容器创建完成");

        System.out.println("关闭容器");
        applicationContext.close();
    }
}
car constructor.....
容器创建完成
关闭容器

指定初始化和销毁方法

@Configuration
public class MainConfigLifeCycle {


    @Bean(initMethod = "init",destroyMethod = "destory")
    public Car car (){
        return new Car();
    }
}
car constructor.....
car init....
容器创建完成
关闭容器
九月 18, 2019 10:57:23 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2eafffde: startup date [Wed Sep 18 22:57:22 CST 2019]; root of context hierarchy
car destory....

指定bean为多实例

@Configuration
public class MainConfigLifeCycle {

    @Scope("prototype")
    @Bean(initMethod = "init",destroyMethod = "destory")
    public Car car (){
        return new Car();
    }
}
public class IocTest_LiftCycle {

    @Test
    public void test01(){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigLifeCycle.class);
        System.out.println("容器创建完成");

        System.out.println("获取bean");
        applicationContext.getBean("car");

        System.out.println("关闭容器");
        applicationContext.close();
    }
}
容器创建完成
获取bean
car constructor.....
car init....
关闭容器
九月 18, 2019 10:59:23 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2eafffde: startup date [Wed Sep 18 22:59:22 CST 2019]; root of context hierarchy

Process finished with exit code 0

2.2 InitializingBean 和 DisposableBean接口

@Component
public class Cat implements InitializingBean, DisposableBean {

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

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

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("cat init....");
    }
}
@ComponentScan("life")
//@Configuration
public class MainConfigLifeCycle {

    @Scope("prototype")
    @Bean(initMethod = "init",destroyMethod = "destory")
    public Car car (){
        return new Car();
    }
}
public class IocTest_LiftCycle {

    @Test
    public void test01(){
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigLifeCycle.class);
        System.out.println("容器创建完成");

        System.out.println("关闭容器");
        applicationContext.close();
    }
}
cat constructor.....
cat init....
容器创建完成
获取bean
关闭容器
九月 18, 2019 11:09:18 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2eafffde: startup date [Wed Sep 18 23:09:17 CST 2019]; root of context hierarchy
cat destory....

2.3 @PostConstruct 和 @PreDestroy

使用JSR250规范定义的注解:

@Component
public class Dog {
    public Dog() {
        System.out.println("Dog Construct...");
    }
    @PostConstruct
    public void init() {
        System.out.println("Dog init...");
    }

    @PreDestroy
    public void destory() {
        System.out.println("Dog destory....");
    }
}

Dog Construct...
Dog init...
容器创建完成
关闭容器
九月 18, 2019 11:17:22 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2eafffde: startup date [Wed Sep 18 23:17:22 CST 2019]; root of context hierarchy
Dog destory....

Process finished with exit code 0

2.4 BeanPostProcessor接口

bean的后置处理器
postProcessBeforeInitialization:初始化之前
postProcessAfterInitialization:初始化之后

//将后置处理器加入到容器中进行工作
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        System.out.println("postProcessBeforeInitialization ...."+ o);
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        System.out.println("postProcessAfterInitialization ...."+ o);
        return o;
    }
}
postProcessBeforeInitialization ....org.springframework.context.event.EventListenerMethodProcessor@68ceda24
postProcessAfterInitialization ....org.springframework.context.event.EventListenerMethodProcessor@68ceda24
postProcessBeforeInitialization ....org.springframework.context.event.DefaultEventListenerFactory@35a50a4c
postProcessAfterInitialization ....org.springframework.context.event.DefaultEventListenerFactory@35a50a4c
postProcessBeforeInitialization ....config.MainConfigLifeCycle@1f021e6c
postProcessAfterInitialization ....config.MainConfigLifeCycle@1f021e6c
cat constructor.....
postProcessBeforeInitialization ....life.Cat@4516af24
cat init....
postProcessAfterInitialization ....life.Cat@4516af24
Dog Construct...
postProcessBeforeInitialization ....life.Dog@44a3ec6b
Dog init...
postProcessAfterInitialization ....life.Dog@44a3ec6b
容器创建完成
关闭容器
九月 18, 2019 11:36:26 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2eafffde: startup date [Wed Sep 18 23:36:26 CST 2019]; root of context hierarchy
Dog destory....
cat destory....

2.5 BeanPostProcessor原理

1、打断点、以Debug方式运行,查看方法调用栈
Spring Bean的生命周期_第1张图片

try {
			//对bean进行属性赋值
            this.populateBean(beanName, mbd, instanceWrapper);
            if (exposedObject != null) {
            	//执行初始化方法
                exposedObject = this.initializeBean(beanName, exposedObject, mbd);
            }
        }

Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
        	//初始化之前先调用ProcessorsBeforeInitialization
            wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
        }

        try {
        	//执行初始化
            this.invokeInitMethods(beanName, wrappedBean, mbd);
        } catch (Throwable var6) {
            throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
        }

        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }
//遍历所有的 BeanPostProcessor类
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        Iterator var4 = this.getBeanPostProcessors().iterator();

        do {
            if (!var4.hasNext()) {
                return result;
            }

            BeanPostProcessor beanProcessor = (BeanPostProcessor)var4.next();
            result = beanProcessor.postProcessBeforeInitialization(result, beanName);
        } while(result != null);

        return result;
    }

2.6 BeanPostProcessor在Spring底层的使用

public interface BeanPostProcessor {
    Object postProcessBeforeInitialization(Object var1, String var2) throws BeansException;

    Object postProcessAfterInitialization(Object var1, String var2) throws BeansException;
}

1、 ApplicationContextAwareProcessor 实现类:是往bean中注入Spring容器

@Component
public class Dog  implements ApplicationContextAware {
    ApplicationContext applicationContext;
    public Dog() {
        System.out.println("Dog Construct...");
    }
    @PostConstruct
    public void init() {
        System.out.println("Dog init...");
    }

    @PreDestroy
    public void destory() {
        System.out.println("Dog destory....");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
class ApplicationContextAwareProcessor implements BeanPostProcessor {

	private final ConfigurableApplicationContext applicationContext;

	private final StringValueResolver embeddedValueResolver;


	/**
	 * Create a new ApplicationContextAwareProcessor for the given context.
	 */
	public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
		this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
	}


	@Override
	public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
		AccessControlContext acc = null;

		if (System.getSecurityManager() != null &&
				(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
						bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
						bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
						//如果bean实现了ApplicationContextAware接口,进行赋值
			acc = this.applicationContext.getBeanFactory().getAccessControlContext();
		}

		if (acc != null) {
			AccessController.doPrivileged(new PrivilegedAction<Object>() {
				@Override
				public Object run() {
					invokeAwareInterfaces(bean);
					return null;
				}
			}, acc);
		}
		else {
			invokeAwareInterfaces(bean);
		}

		return bean;
	}

	private void invokeAwareInterfaces(Object bean) {
		if (bean instanceof Aware) {
			if (bean instanceof EnvironmentAware) {
				((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
			}
			if (bean instanceof EmbeddedValueResolverAware) {
				((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
			}
			if (bean instanceof ResourceLoaderAware) {
				((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
			}
			if (bean instanceof ApplicationEventPublisherAware) {
				((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
			}
			if (bean instanceof MessageSourceAware) {
				((MessageSourceAware) bean).setMessageSource(this.applicationContext);
			}
			if (bean instanceof ApplicationContextAware) {
				((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
			}
		}
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		return bean;
	}

}

2、 BeanValidationPostProcessor 实现类:bean初始化完之后进行数据校验

public class BeanValidationPostProcessor implements BeanPostProcessor, InitializingBean {
    private Validator validator;
    private boolean afterInitialization = false;

    public BeanValidationPostProcessor() {
    }

    public void setValidator(Validator validator) {
        this.validator = validator;
    }

    public void setValidatorFactory(ValidatorFactory validatorFactory) {
        this.validator = validatorFactory.getValidator();
    }

    public void setAfterInitialization(boolean afterInitialization) {
        this.afterInitialization = afterInitialization;
    }

    public void afterPropertiesSet() {
        if (this.validator == null) {
            this.validator = Validation.buildDefaultValidatorFactory().getValidator();
        }

    }

    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (!this.afterInitialization) {
            this.doValidate(bean);
        }

        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (this.afterInitialization) {
            this.doValidate(bean);
        }

        return bean;
    }

    protected void doValidate(Object bean) {
        Set<ConstraintViolation<Object>> result = this.validator.validate(bean, new Class[0]);
        if (!result.isEmpty()) {
            StringBuilder sb = new StringBuilder("Bean state is invalid: ");
            Iterator it = result.iterator();

            while(it.hasNext()) {
                ConstraintViolation<Object> violation = (ConstraintViolation)it.next();
                sb.append(violation.getPropertyPath()).append(" - ").append(violation.getMessage());
                if (it.hasNext()) {
                    sb.append("; ");
                }
            }

            throw new BeanInitializationException(sb.toString());
        }
    }
}

3、 InitDestroyAnnotationBeanPostProcessor 实现类:处理@PostConstruct注解的
4、 AutowiredAnnotationBeanPostProcessor 实现类:处理@AutoWired注解的

你可能感兴趣的:(SpringSource)