Spring Bean 生命周期

逆流者 2021年04月11日 81次浏览

新建 maven 项目,引入spring 依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.5</version>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>RELEASE</version>
    <scope>test</scope>
</dependency>

@Bean 初始化和销毁方法

public class Red {

    public Red() {
        System.out.println("red constructor...");
    }

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

    public void destroy() {
        System.out.println("red ... destroy...");
    }
}
@Configuration
public class LifeCycleConfig {

    @Bean(initMethod = "init", destroyMethod = "destroy")
    public Red red() {
        return new Red();
    }
}
public class LifeCycleTest {

    @Test
    public void initAndDestroy() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
        System.out.println("IOC 容器 创建完成...");
        context.close();
        System.out.println("IOC 容器 关闭...");
    }
}
red constructor...
red ... init...
IOC 容器 创建完成...
red ... destroy...
IOC 容器 关闭...

上面Red Bean 默认是单例的,所以在IOC 容器 创建完成之前就已经完成构造器和init方法的调用了。

下面再看下多实例的效果:

标注多实例(@Scope("prototype"))

@Scope("prototype")
@Bean(initMethod = "init", destroyMethod = "destroy")
public Red red() {
    return new Red();
}

直接执行上面的测试:

IOC 容器 创建完成...
IOC 容器 关闭...

这是发现对象并没有初始化以及destroy。

修改一下测试方法,获取一下red的bean:

@Test
public void initAndDestroy() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
    System.out.println("IOC 容器 创建完成...");
    Red red = context.getBean(Red.class);
    System.out.println(red);
    context.close();
    System.out.println("IOC 容器 关闭...");
}
IOC 容器 创建完成...
red constructor...
red ... init...
top.wushanghui.annotation.entity.Red@fba92d3
IOC 容器 关闭...

如果是多实例的bean 是在获取的时候才初始化bean的。

InitializingBean和DisposableBean

@Component
public class Blue implements InitializingBean, DisposableBean {

    public Blue() {
        System.out.println("blue constructor...");
    }

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

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

把上面标注Component注解的类扫描的方式加到容器中:

@ComponentScan("top.wushanghui.annotation.entity")
@Configuration
public class LifeCycleConfig {
@Test
public void testInitializingBeanAndDisposableBean() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
    System.out.println("IOC 容器 创建完成...");
    context.close();
    System.out.println("IOC 容器 关闭...");
}
blue constructor...
blue afterPropertiesSet...
IOC 容器 创建完成...
blue destroy...
IOC 容器 关闭...

JSR250 的@PostConstruct和@PreDestroy

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


    public Yellow() {
        System.out.println("yellow constructor...");
    }

    //对象创建并赋值之后调用
    @PostConstruct
    public void init() {
        System.out.println("yellow....@PostConstruct...");
    }

    //容器移除对象之前
    @PreDestroy
    public void detory() {
        System.out.println("yellow....@PreDestroy...");
    }
}
@Test
public void testPostConstructAndPreDestroy() {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
    System.out.println("IOC 容器 创建完成...");
    context.close();
    System.out.println("IOC 容器 关闭...");
}
blue constructor...
blue afterPropertiesSet...
yellow constructor...
yellow....@PostConstruct...
red constructor...
red ... init...
IOC 容器 创建完成...
red ... destroy...
yellow....@PreDestroy...
blue destroy...
IOC 容器 关闭...

BeanPostProcessor

bean的后置处理器:

  • 在bean初始化前后进行一些处理工作;
  • postProcessBeforeInitialization:在初始化之前工作
  • postProcessAfterInitialization:在初始化之后工作
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization beanName: " + beanName + ", bean: " + bean);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization: " + beanName + ", bean: " + bean);
        return bean;
    }
}
postProcessBeforeInitialization beanName: lifeCycleConfig, bean: top.wushanghui.annotation.config.LifeCycleConfig$$EnhancerBySpringCGLIB$$2da7cc30@2a54a73f
postProcessAfterInitialization: lifeCycleConfig, bean: top.wushanghui.annotation.config.LifeCycleConfig$$EnhancerBySpringCGLIB$$2da7cc30@2a54a73f
blue constructor...
postProcessBeforeInitialization beanName: blue, bean: top.wushanghui.annotation.entity.Blue@505fc5a4
blue afterPropertiesSet...
postProcessAfterInitialization: blue, bean: top.wushanghui.annotation.entity.Blue@505fc5a4
yellow constructor...
postProcessBeforeInitialization beanName: yellow, bean: top.wushanghui.annotation.entity.Yellow@156b88f5
yellow....@PostConstruct...
postProcessAfterInitialization: yellow, bean: top.wushanghui.annotation.entity.Yellow@156b88f5
red constructor...
postProcessBeforeInitialization beanName: red, bean: top.wushanghui.annotation.entity.Red@1a18644
red ... init...
postProcessAfterInitialization: red, bean: top.wushanghui.annotation.entity.Red@1a18644
IOC 容器 创建完成...
red ... destroy...
yellow....@PreDestroy...
blue destroy...
IOC 容器 关闭...

BeanPostProcessor 原理

从 AnnotationConfigApplicationContext 类的有参构造器
-> refresh()
-> finishBeanFactoryInitialization(beanFactory) 实例化所有剩余的(非延迟初始化)单例
-> 调用AbstractApplicationContext类的 finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)方法
-> 调用 DefaultListableBeanFactory 类的 preInstantiateSingletons() 方法
-> 调用 AbstractBeanFactory 类的 getBean(String name)
-> doGetBean()
-> 调用 DefaultSingletonBeanRegistry 类的 getSingleton()
-> 调用 AbstractAutowireCapableBeanFactory 类的 createBean() -> doCreateBean()

看到此处代码

 // 给bean进行属性赋值
this.populateBean(beanName, mbd, instanceWrapper);
// 初始化
exposedObject = this.initializeBean(beanName, exposedObject, mbd);

-> initializeBean()

if (mbd == null || !mbd.isSynthetic()) {
	// 初始化之前调用 
    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;挨个执行beforeInitialization,
一但返回null,跳出for循环,不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization

public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;

    Object current;
    for(Iterator var4 = this.getBeanPostProcessors().iterator(); var4.hasNext(); result = current) {
        BeanPostProcessor processor = (BeanPostProcessor)var4.next();
        current = processor.postProcessBeforeInitialization(result, beanName);
        if (current == null) {
        	// 为null,跳出循环,后面的BeanPostProcessor.postProcessorsBeforeInitialization 就不会执行了
            return result;
        }
    }

    return result;
}

Spring底层对 BeanPostProcessor 的应用

下图中除了我自己定义的MyBeanPostProcessor ,其他的都是Spring底层对 BeanPostProcessor 的应用
在这里插入图片描述

也附上文字版,方便复制

AdvisorAdapterRegistrationManager (org.springframework.aop.framework.adapter)
MyBeanPostProcessor (top.wushanghui.annotation.entity) // 我自己定义的
BeanPostProcessorChecker in PostProcessorRegistrationDelegate (org.springframework.context.support)
LoadTimeWeaverAwareProcessor (org.springframework.context.weaving)
AbstractAdvisingBeanPostProcessor (org.springframework.aop.framework)
    AbstractBeanFactoryAwareAdvisingPostProcessor (org.springframework.aop.framework.autoproxy)
        MethodValidationPostProcessor (org.springframework.validation.beanvalidation)
        AsyncAnnotationBeanPostProcessor (org.springframework.scheduling.annotation) // 处理Async注解的,异步方法
DestructionAwareBeanPostProcessor (org.springframework.beans.factory.config)
    ScheduledAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
    InitDestroyAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation) // 用来处理@PostConstruct和@PreDestroy 这两个注解的,
        CommonAnnotationBeanPostProcessor (org.springframework.context.annotation)
    ApplicationListenerDetector (org.springframework.context.support)
ApplicationContextAwareProcessor (org.springframework.context.support) // 用来给组件注入IOC 容器
MergedBeanDefinitionPostProcessor (org.springframework.beans.factory.support)
    ScheduledAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
    InitDestroyAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
        CommonAnnotationBeanPostProcessor (org.springframework.context.annotation)
    RequiredAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
    AutowiredAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
    ApplicationListenerDetector (org.springframework.context.support)
BeanValidationPostProcessor (org.springframework.validation.beanvalidation) // 对属性的校验
InstantiationAwareBeanPostProcessor (org.springframework.beans.factory.config)
    SmartInstantiationAwareBeanPostProcessor (org.springframework.beans.factory.config)
        ScriptFactoryPostProcessor (org.springframework.scripting.support)
        RequiredAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
        AutowiredAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation) // 处理Autowired 注解,我们为什么标了@Autowired 就能自动装配好呢,都是AutowiredAnnotationBeanPostProcessor 帮我们处理的
        InstantiationAwareBeanPostProcessorAdapter (org.springframework.beans.factory.config)
        AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)
            BeanNameAutoProxyCreator (org.springframework.aop.framework.autoproxy)
            AbstractAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
                DefaultAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
                AspectJAwareAdvisorAutoProxyCreator (org.springframework.aop.aspectj.autoproxy)
                    AnnotationAwareAspectJAutoProxyCreator (org.springframework.aop.aspectj.annotation)
                InfrastructureAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
    ImportAwareBeanPostProcessor in ConfigurationClassPostProcessor (org.springframework.context.annotation)
    CommonAnnotationBeanPostProcessor (org.springframework.context.annotation)

上面有很多spring 对 BeanPostProcessor 的应用,我们看其中一个来具体分析下,ApplicationContextAwareProcessor ,怎么样才能给我们自己定义bean 注入 IOC容器呢?

/**
 * {@link BeanPostProcessor} implementation that supplies the {@code ApplicationContext},
 * {@link org.springframework.core.env.Environment Environment}, or
 * {@link StringValueResolver} for the {@code ApplicationContext} to beans that
 * implement the {@link EnvironmentAware}, {@link EmbeddedValueResolverAware},
 * {@link ResourceLoaderAware}, {@link ApplicationEventPublisherAware},
 * {@link MessageSourceAware}, and/or {@link ApplicationContextAware} interfaces.
 *
 * <p>Implemented interfaces are satisfied in the order in which they are
 * mentioned above.
 *
 * <p>Application contexts will automatically register this with their underlying bean factory. Applications do not use this directly.
 *
 * @author Juergen Hoeller
 * @author Costin Leau
 * @author Chris Beams
 * @since 10.10.2003
 * @see org.springframework.context.EnvironmentAware
 * @see org.springframework.context.EmbeddedValueResolverAware
 * @see org.springframework.context.ResourceLoaderAware
 * @see org.springframework.context.ApplicationEventPublisherAware
 * @see org.springframework.context.MessageSourceAware
 * @see org.springframework.context.ApplicationContextAware
 * @see org.springframework.context.support.AbstractApplicationContext#refresh()
 */
class ApplicationContextAwareProcessor implements BeanPostProcessor {

	private final ConfigurableApplicationContext applicationContext;

	private final StringValueResolver embeddedValueResolver;


	/**
	 * 为给定上下文创建一个新的ApplicationContextAwareProcessor。
	 */
	public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
		this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
	}


	@Override
	@Nullable
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		// 如果bean不是以下 XxxxAware 的实例的话,直接返回当前bean
		if (!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
				bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
				bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware ||
				bean instanceof ApplicationStartupAware)) {
			return bean;
		}

		AccessControlContext acc = null;

		if (System.getSecurityManager() != null) {
			acc = this.applicationContext.getBeanFactory().getAccessControlContext();
		}

		if (acc != null) {
			AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
				invokeAwareInterfaces(bean);
				return null;
			}, acc);
		}
		else {
			invokeAwareInterfaces(bean);
		}

		return bean;
	}

	// 给当前bean set applicationContext
	private void invokeAwareInterfaces(Object bean) {
		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 ApplicationStartupAware) {
			((ApplicationStartupAware) bean).setApplicationStartup(this.applicationContext.getApplicationStartup());
		}
		// 如果是实现了ApplicationContextAware 接口的bean,给这个bean 注入applicationContext
		if (bean instanceof ApplicationContextAware) {
			((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
		}
	}

}

看了上面源码就知道怎么给自己定义bean 注入 IOC容器了。

定义一个ApplicationContextAware 接口的实现类

@Component
public class Green implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

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

测试一下是否注入了ApplicationContext :

@Test
public void testApplicationContextAware() {
    ApplicationContext context = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
    Green bean = context.getBean(Green.class);
    System.out.println(context);
    System.out.println(bean.getApplicationContext());
    System.out.println(context == bean.getApplicationContext());
}
org.springframework.context.annotation.AnnotationConfigApplicationContext@1e4a7dd4, started on Sun Apr 11 10:04:39 CST 2021
org.springframework.context.annotation.AnnotationConfigApplicationContext@1e4a7dd4, started on Sun Apr 11 10:04:39 CST 2021
true

Spring定义了很多XxxxAware以及XxxxAware相关功能的实现类:

在这里插入图片描述

文字全列出来,方便复制:

ApplicationEventPublisherAware (org.springframework.context)
    EventPublicationInterceptor (org.springframework.context.event)
MessageSourceAware (org.springframework.context)
ResourceLoaderAware (org.springframework.context)
    ReloadableResourceBundleMessageSource (org.springframework.context.support)
    ConfigurationClassPostProcessor (org.springframework.context.annotation)
    ScriptFactoryPostProcessor (org.springframework.scripting.support)
    ClassPathScanningCandidateComponentProvider (org.springframework.context.annotation)
        ClassPathBeanDefinitionScanner (org.springframework.context.annotation)
ApplicationStartupAware (org.springframework.context)
    ConfigurationClassPostProcessor (org.springframework.context.annotation)
NotificationPublisherAware (org.springframework.jmx.export.notification)
BeanFactoryAware (org.springframework.beans.factory)
    AnnotationJmxAttributeSource (org.springframework.jmx.export.annotation)
    AbstractBeanFactoryAwareAdvisingPostProcessor (org.springframework.aop.framework.autoproxy)
        MethodValidationPostProcessor (org.springframework.validation.beanvalidation)
        AsyncAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
    AbstractBeanFactoryBasedTargetSourceCreator (org.springframework.aop.framework.autoproxy.target)
        QuickTargetSourceCreator (org.springframework.aop.framework.autoproxy.target)
        LazyInitTargetSourceCreator (org.springframework.aop.framework.autoproxy.target)
    ScriptFactoryPostProcessor (org.springframework.scripting.support)
    PropertyPathFactoryBean (org.springframework.beans.factory.config)
    SimpleBeanFactoryAwareAspectInstanceFactory (org.springframework.aop.config)
    AbstractApplicationEventMulticaster (org.springframework.context.event)
        SimpleApplicationEventMulticaster (org.springframework.context.event)
    AbstractFactoryBean (org.springframework.beans.factory.config)
        MapFactoryBean (org.springframework.beans.factory.config)
        ListFactoryBean (org.springframework.beans.factory.config)
        SetFactoryBean (org.springframework.beans.factory.config)
        ObjectFactoryCreatingFactoryBean (org.springframework.beans.factory.config)
        ProviderCreatingFactoryBean (org.springframework.beans.factory.config)
        AbstractServiceLoaderBasedFactoryBean (org.springframework.beans.factory.serviceloader)
            ServiceListFactoryBean (org.springframework.beans.factory.serviceloader)
            ServiceLoaderFactoryBean (org.springframework.beans.factory.serviceloader)
            ServiceFactoryBean (org.springframework.beans.factory.serviceloader)
    EnhancedConfiguration in ConfigurationClassEnhancer (org.springframework.context.annotation)
    ScheduledAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
    CommonAnnotationBeanPostProcessor (org.springframework.context.annotation)
    GroovyScriptFactory (org.springframework.scripting.groovy)
    AbstractBeanFactoryPointcutAdvisor (org.springframework.aop.support)
        DefaultBeanFactoryPointcutAdvisor (org.springframework.aop.support)
        BeanFactoryCacheOperationSourceAdvisor (org.springframework.cache.interceptor)
    ServiceLocatorFactoryBean (org.springframework.beans.factory.config)
    AsyncExecutionAspectSupport (org.springframework.aop.interceptor)
        AsyncExecutionInterceptor (org.springframework.aop.interceptor)
            AnnotationAsyncExecutionInterceptor (org.springframework.scheduling.annotation)
    CacheAspectSupport (org.springframework.cache.interceptor)
        CacheInterceptor (org.springframework.cache.interceptor)
    MethodLocatingFactoryBean (org.springframework.aop.config)
    AbstractBeanFactoryBasedTargetSource (org.springframework.aop.target)
        SimpleBeanTargetSource (org.springframework.aop.target)
        LazyInitTargetSource (org.springframework.aop.target)
            NotificationPublisherAwareLazyTargetSource in MBeanExporter (org.springframework.jmx.export)
        AbstractPrototypeBasedTargetSource (org.springframework.aop.target)
            AbstractPoolingTargetSource (org.springframework.aop.target)
                CommonsPool2TargetSource (org.springframework.aop.target)
            ThreadLocalTargetSource (org.springframework.aop.target)
            PrototypeTargetSource (org.springframework.aop.target)
    MBeanExporter (org.springframework.jmx.export)
        AnnotationMBeanExporter (org.springframework.jmx.export.annotation)
    MethodInvokingBean (org.springframework.beans.factory.config)
        MethodInvokingFactoryBean (org.springframework.beans.factory.config)
    ProxyFactoryBean (org.springframework.aop.framework)
    JndiObjectFactoryBean (org.springframework.jndi)
    AsyncAnnotationAdvisor (org.springframework.scheduling.annotation)
    GenericTypeAwareAutowireCandidateResolver (org.springframework.beans.factory.support)
        QualifierAnnotationAutowireCandidateResolver (org.springframework.beans.factory.annotation)
            ContextAnnotationAutowireCandidateResolver (org.springframework.context.annotation)
    PlaceholderConfigurerSupport (org.springframework.beans.factory.config)
        PropertySourcesPlaceholderConfigurer (org.springframework.context.support)
        PropertyPlaceholderConfigurer (org.springframework.beans.factory.config)
            PreferencesPlaceholderConfigurer (org.springframework.beans.factory.config)
    AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)
        BeanNameAutoProxyCreator (org.springframework.aop.framework.autoproxy)
        AbstractAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
            DefaultAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
            AspectJAwareAdvisorAutoProxyCreator (org.springframework.aop.aspectj.autoproxy)
                AnnotationAwareAspectJAutoProxyCreator (org.springframework.aop.aspectj.annotation)
            InfrastructureAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
    DefaultLifecycleProcessor (org.springframework.context.support)
    AspectJExpressionPointcutAdvisor (org.springframework.aop.aspectj)
    RequiredAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
    AutowiredAnnotationBeanPostProcessor (org.springframework.beans.factory.annotation)
    ScopedProxyFactoryBean (org.springframework.aop.scope)
    MBeanExportConfiguration (org.springframework.context.annotation)
    LoadTimeWeaverAwareProcessor (org.springframework.context.weaving)
    CacheProxyFactoryBean (org.springframework.cache.interceptor)
    AspectJExpressionPointcut (org.springframework.aop.aspectj)
    BeanConfigurerSupport (org.springframework.beans.factory.wiring)
EnvironmentAware (org.springframework.context)
    ConfigurationClassPostProcessor (org.springframework.context.annotation)
    PropertySourcesPlaceholderConfigurer (org.springframework.context.support)
    MBeanExportConfiguration (org.springframework.context.annotation)
EmbeddedValueResolverAware (org.springframework.context)
    ScheduledAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
    FormattingConversionServiceFactoryBean (org.springframework.format.support)
    FormattingConversionService (org.springframework.format.support)
        DefaultFormattingConversionService (org.springframework.format.support)
    EmbeddedValueResolutionSupport (org.springframework.context.support)
        NumberFormatAnnotationFormatterFactory (org.springframework.format.number)
        Jsr354NumberFormatAnnotationFormatterFactory (org.springframework.format.number.money)
        JodaDateTimeFormatAnnotationFormatterFactory (org.springframework.format.datetime.joda)
        DateTimeFormatAnnotationFormatterFactory (org.springframework.format.datetime)
        Jsr310DateTimeFormatAnnotationFormatterFactory (org.springframework.format.datetime.standard)
ImportAware (org.springframework.context.annotation)
    AbstractAsyncConfiguration (org.springframework.scheduling.annotation)
        ProxyAsyncConfiguration (org.springframework.scheduling.annotation)
    AbstractCachingConfiguration (org.springframework.cache.annotation)
        ProxyCachingConfiguration (org.springframework.cache.annotation)
    LoadTimeWeavingConfiguration (org.springframework.context.annotation)
    MBeanExportConfiguration (org.springframework.context.annotation)
LoadTimeWeaverAware (org.springframework.context.weaving)
    AspectJWeavingEnabler (org.springframework.context.weaving)
BeanNameAware (org.springframework.beans.factory)
    ScheduledAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
    ExecutorConfigurationSupport (org.springframework.scheduling.concurrent)
        ThreadPoolTaskExecutor (org.springframework.scheduling.concurrent)
        ScheduledExecutorFactoryBean (org.springframework.scheduling.concurrent)
        ThreadPoolExecutorFactoryBean (org.springframework.scheduling.concurrent)
        ThreadPoolTaskScheduler (org.springframework.scheduling.concurrent)
    ConcurrentMapCacheFactoryBean (org.springframework.cache.concurrent)
    PropertyPathFactoryBean (org.springframework.beans.factory.config)
    DefaultAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
    TaskExecutorFactoryBean (org.springframework.scheduling.config)
    PlaceholderConfigurerSupport (org.springframework.beans.factory.config)
        PropertySourcesPlaceholderConfigurer (org.springframework.context.support)
        PropertyPlaceholderConfigurer (org.springframework.beans.factory.config)
            PreferencesPlaceholderConfigurer (org.springframework.beans.factory.config)
    FieldRetrievingFactoryBean (org.springframework.beans.factory.config)
    AbstractRefreshableConfigApplicationContext (org.springframework.context.support)
        AbstractXmlApplicationContext (org.springframework.context.support)
            FileSystemXmlApplicationContext (org.springframework.context.support)
            ClassPathXmlApplicationContext (org.springframework.context.support)
BeanClassLoaderAware (org.springframework.beans.factory)
    MBeanProxyFactoryBean (org.springframework.jmx.access)
    JndiRmiProxyFactoryBean (org.springframework.remoting.rmi)
    DefaultContextLoadTimeWeaver (org.springframework.context.weaving)
    ScriptFactoryPostProcessor (org.springframework.scripting.support)
    BshScriptFactory (org.springframework.scripting.bsh)
    LocalStatelessSessionProxyFactoryBean (org.springframework.ejb.access)
    AbstractApplicationEventMulticaster (org.springframework.context.event)
        SimpleApplicationEventMulticaster (org.springframework.context.event)
    StandardScriptFactory (org.springframework.scripting.support)
    ConcurrentMapCacheManager (org.springframework.cache.concurrent)
    AbstractFactoryBean (org.springframework.beans.factory.config)
        MapFactoryBean (org.springframework.beans.factory.config)
        ListFactoryBean (org.springframework.beans.factory.config)
        SetFactoryBean (org.springframework.beans.factory.config)
        ObjectFactoryCreatingFactoryBean (org.springframework.beans.factory.config)
        ProviderCreatingFactoryBean (org.springframework.beans.factory.config)
        AbstractServiceLoaderBasedFactoryBean (org.springframework.beans.factory.serviceloader)
            ServiceListFactoryBean (org.springframework.beans.factory.serviceloader)
            ServiceLoaderFactoryBean (org.springframework.beans.factory.serviceloader)
            ServiceFactoryBean (org.springframework.beans.factory.serviceloader)
    ResourceBundleMessageSource (org.springframework.context.support)
    ResourceBundleThemeSource (org.springframework.ui.context.support)
    SimpleRemoteStatelessSessionProxyFactoryBean (org.springframework.ejb.access)
    GroovyScriptFactory (org.springframework.scripting.groovy)
    MBeanServerConnectionFactoryBean (org.springframework.jmx.support)
    ProxyProcessorSupport (org.springframework.aop.framework)
        AbstractAdvisingBeanPostProcessor (org.springframework.aop.framework)
            AbstractBeanFactoryAwareAdvisingPostProcessor (org.springframework.aop.framework.autoproxy)
                MethodValidationPostProcessor (org.springframework.validation.beanvalidation)
                AsyncAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
        AbstractAutoProxyCreator (org.springframework.aop.framework.autoproxy)
            BeanNameAutoProxyCreator (org.springframework.aop.framework.autoproxy)
            AbstractAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
                DefaultAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
                AspectJAwareAdvisorAutoProxyCreator (org.springframework.aop.aspectj.autoproxy)
                    AnnotationAwareAspectJAutoProxyCreator (org.springframework.aop.aspectj.annotation)
                InfrastructureAdvisorAutoProxyCreator (org.springframework.aop.framework.autoproxy)
    InterfaceBasedMBeanInfoAssembler (org.springframework.jmx.export.assembler)
    MBeanExporter (org.springframework.jmx.export)
        AnnotationMBeanExporter (org.springframework.jmx.export.annotation)
    FieldRetrievingFactoryBean (org.springframework.beans.factory.config)
    MethodInvokingBean (org.springframework.beans.factory.config)
        MethodInvokingFactoryBean (org.springframework.beans.factory.config)
    ProxyFactoryBean (org.springframework.aop.framework)
    ServiceLoaderFactoryBean (org.springframework.beans.factory.serviceloader)
    BshScriptEvaluator (org.springframework.scripting.bsh)
    JndiObjectFactoryBean (org.springframework.jndi)
    LoadTimeWeavingConfiguration (org.springframework.context.annotation)
    MethodInvokingRunnable (org.springframework.scheduling.support)
    AspectJWeavingEnabler (org.springframework.context.weaving)
    RmiProxyFactoryBean (org.springframework.remoting.rmi)
    ServiceFactoryBean (org.springframework.beans.factory.serviceloader)
    CustomScopeConfigurer (org.springframework.beans.factory.config)
    AbstractSingletonProxyFactoryBean (org.springframework.aop.framework)
        CacheProxyFactoryBean (org.springframework.cache.interceptor)
    RemotingSupport (org.springframework.remoting.support)
        RemoteExporter (org.springframework.remoting.support)
            RemoteInvocationBasedExporter (org.springframework.remoting.support)
                RemoteInvocationSerializingExporter (org.springframework.remoting.rmi)
                RmiBasedExporter (org.springframework.remoting.rmi)
                    JndiRmiServiceExporter (org.springframework.remoting.rmi)
                    RmiServiceExporter (org.springframework.remoting.rmi)
        RemoteAccessor (org.springframework.remoting.support)
            UrlBasedRemoteAccessor (org.springframework.remoting.support)
                RemoteInvocationBasedAccessor (org.springframework.remoting.support)
                    RmiClientInterceptor (org.springframework.remoting.rmi)
                        RmiProxyFactoryBean (org.springframework.remoting.rmi)
    ServiceListFactoryBean (org.springframework.beans.factory.serviceloader)
    ConfigurationClassPostProcessor (org.springframework.context.annotation)
    CustomAutowireConfigurer (org.springframework.beans.factory.annotation)
    GroovyScriptEvaluator (org.springframework.scripting.groovy)
    MBeanClientInterceptor (org.springframework.jmx.access)
        MBeanProxyFactoryBean (org.springframework.jmx.access)
    StandardScriptEvaluator (org.springframework.scripting.support)
    AbstractServiceLoaderBasedFactoryBean (org.springframework.beans.factory.serviceloader)
        ServiceListFactoryBean (org.springframework.beans.factory.serviceloader)
        ServiceLoaderFactoryBean (org.springframework.beans.factory.serviceloader)
        ServiceFactoryBean (org.springframework.beans.factory.serviceloader)
ApplicationContextAware (org.springframework.context)
    ScheduledAnnotationBeanPostProcessor (org.springframework.scheduling.annotation)
    Green (top.wushanghui.annotation.entity)
    LiveBeansView (org.springframework.context.support)
    EventListenerMethodProcessor (org.springframework.context.event)
    LocalValidatorFactoryBean (org.springframework.validation.beanvalidation)
        OptionalValidatorFactoryBean (org.springframework.validation.beanvalidation)
    ApplicationObjectSupport (org.springframework.context.support)

总结

文章
https://snailclimb.gitee.io/javaguide/#/docs/system-design/framework/spring/Spring%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98%E6%80%BB%E7%BB%93?id=_5-spring-bean

中总结到:

  1. Bean 容器找到配置文件中 Spring Bean 的定义。
  2. Bean 容器利用 Java Reflection API 创建一个Bean的实例。
  3. 如果涉及到一些属性值 利用 set()方法设置一些属性值。
  4. 如果 Bean 实现了 BeanNameAware 接口,调用 setBeanName()方法,传入Bean的名字。
  5. 如果 Bean 实现了 BeanClassLoaderAware 接口,调用 setBeanClassLoader()方法,传入 ClassLoader对象的实例。
  6. 与上面的类似,如果实现了其他 *.Aware接口,就调用相应的方法。
  7. 如果有和加载这个 Bean 的 Spring 容器相关的 BeanPostProcessor 对象,执行postProcessBeforeInitialization() 方法
  8. 如果Bean实现了InitializingBean接口,执行afterPropertiesSet()方法。
  9. 如果 Bean 在配置文件中的定义包含 init-method 属性,执行指定的方法。
  10. 如果有和加载这个 Bean的 Spring 容器相关的 BeanPostProcessor 对象,执行postProcessAfterInitialization() 方法
  11. 当要销毁 Bean 的时候,如果 Bean 实现了 DisposableBean 接口,执行 destroy() 方法。
  12. 当要销毁 Bean 的时候,如果 Bean 在配置文件中的定义包含 destroy-method 属性,执行指定的方法。

在这里插入图片描述