LifeCycleBean.class
public class LifeCycleBean { public static final Logger logger = LoggerFactory.getLogger(LifeCycleBean.class); public LifeCycleBean() { logger.info("lifecycle 构造函数"); } @Autowired //字符串类型默认不会做依赖注入,加@value 会在环境变量或者配置文件里面找。 //其他类型的注入会直接在 容器里面查找对应的类型做依赖注入 public void autowire (@Value("${JAVA_HOME}") String home){ logger.info("依赖注入:",home); } @PostConstruct public void init(){ logger.info("初始化"); } @PreDestroy //只有单例类型会在这里被销毁,其他另有时间 public void destroy(){ logger.info("销毁--"); } }
myBeanPostProcessor.class
@component public class myBeanPostProcessor implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor { public static final Logger logger = LoggerFactory.getLogger(LifeCycleBean.class); @Override public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { if (beanName.equals("lifeCycleBean")){ logger.info("销毁之前执行的方法 ,如 @preDestroy"); } } @Override public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException { if (beanName.equals("lifeCycleBean")){ logger.info("bean 实例化之前执行,返回不为 null 的话,会替换原来存在的bean"); } return null; } @Override public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException { if (beanName.equals("lifeCycleBean")){ logger.info("bean 实例化之后执行,返回false 不会进行依赖注入阶段了,一般返回 true"); } return true; } @Override public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException { if (beanName.equals("lifeCycleBean")){ logger.info("依赖注入阶段执行,这里可以追加很多后处理器 比如@autowired、@resource"); } return pvs; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (beanName.equals("lifeCycleBean")){ logger.info("初始化前执行的方法 ,返回的bean会替换原来的对象,这一步可以执行@PostContruct、@ConfigurationProperties"); logger.info("前一个是初始化方法,后一个是springboot 里面 bean的属性和配置类的键值对绑定的注解"); } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (beanName.equals("lifeCycleBean")){ logger.info("初始化之后执行,返回的bean会替换原来的对象,这一步可以执行代理增强等操作"); } return bean; } }