一个受 Spring 管理的 bean,生命周期主要阶段有
package com.mangoubiubiu.show; import lombok.extern.slf4j.Slf4j; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.logging.Logger; @Slf4j @Component public class LifeCycleBean { public LifeCycleBean(){log.info("构造");} @Autowired public void autowire(@Value("${JAVA_HOME}") String home){ log.info("依赖注入:{}",home); } @PostConstruct public void init(){ log.info("初始化"); } @PostConstruct public void destory(){ log.info("销毁"); } }
一些资料会提到,生命周期中还有一类 bean 后处理器:BeanPostProcessor,会在 bean 的初始化的前后,提供一些扩展逻辑。但这种说法是不完整的,见下面的演示1
创建前后的增强
依赖注入前的增强
初始化前后的增强
销毁之前的增强
package com.mangoubiubiu.show; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.beans.PropertyValues; import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; import org.springframework.stereotype.Component; import java.beans.PropertyDescriptor; @Slf4j @Component public class MyBeanPostProcessor implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor { @Override public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { if(beanName.equals("lifeCycleBean")) log.info("<<<<<<<销毁之前执行,如 @PreDestory"); } @Override public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException { if(beanName.equals("lifeCycleBean")) log.info("<<<<<<<实例化之前执行,这里返回的对象会替换掉原本的bean"); return null; } @Override public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { if(beanName.equals("lifeCycleBean")) log.info("<<<<<<<实例化之后执行,这里返回false会跳过依赖注入阶段"); return false; } @Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException { if(beanName.equals("lifeCycleBean")) log.info("<<<<<<<依赖注入阶段执行,如@Autowired 、 @Value、@Resource"); return pvs; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if(beanName.equals("lifeCycleBean")) log.info("<<<<<<初始化之前执行,这里返回的对象会替换掉原本的bean , @PostConstruct、@ConfigurationProperties"); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if(beanName.equals("lifeCycleBean")) log.info("<<<<<<初始化之后执行,这里返回的对象会替换掉原本的bean , 如代理增强"); return null; } }