package com.xkj.org;
import org.slf4j.Logger;
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 javax.annotation.PreDestroy;
@Component
public class LifeCycleBean {
public LifeCycleBean() {
System.out.println(("构造..."));
}
@Autowired
public void autowire(@Value("${JAVA_HOME}") String home) {
System.out.println("依赖注入:"+ home);
}
@PostConstruct
public void init() {
System.out.println("初始化...");
}
@PreDestroy
public void destroy() {
System.out.println("销毁....");
}
}
ConfigurableApplicationContext context = SpringApplication.run(ReggieApplication.class, args);
//关闭容器,观察bean的生命周期
context.close();
执行流程: Bean的构造方法->@Autowired依赖注入->Bean的初始化方法->容器关闭->Bean的销毁方法
扩展点:
package com.xkj.org;
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;
@Component
public class MyBeanPostProcessor implements InstantiationAwareBeanPostProcessor, DestructionAwareBeanPostProcessor {
@Override
public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
if(beanName.equals("lifeCycleBean")) {
System.out.println("销毁之前执行,如@PreDestroy");
}
}
@Override
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if(beanName.equals("lifeCycleBean")) {
System.out.println("实例化之前执行,这里返回的对象不为null会替换掉原本的Bean");
}
return null;
}
@Override
public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
if(beanName.equals("lifeCycleBean")) {
System.out.println("实例化之后执行,这里如果返回false,会跳过依赖注入");
// return false;
}
return true;
}
@Override
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
if(beanName.equals("lifeCycleBean")) {
System.out.println("依赖注入阶段执行,如@Autowired @Value @Resource,扩展的比较多");
}
return pvs;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(beanName.equals("lifeCycleBean")) {
System.out.println("初始化之前执行,这里返回的对象会替换掉原本的bean, 如@PostConstruct @ConfigurationProperties");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if(beanName.equals("lifeCycleBean")) {
System.out.println("初始化之后执行,这里返回的对象会替换掉原本的Bean,如代理增强");
}
return bean;
}
}
标签:生命周期,beanName,System,Bean,org,println,import,public
From: https://blog.csdn.net/qq_36352889/article/details/140191707