spring 容器管理我们的bean ,每个bean 都有自己的生命周期。生命周期,顾名思义,从出生,到死亡的一个时间周期或者过程。spring 提供了一些 接口或者 回调 方法,让我们在 从bean 的出生到死亡的过程中可以对 bean 做一些 事情,比如 设置依赖,配置属性,实例化后可以回调一些方法,销毁的时候也可以回调一些方法。
如果对spring 的一些接口不是很熟悉的化,光看图会有一点懵逼。举个栗子:主要是 看 方法的执行顺序
- BeanTest
package com.example.cloudcustomer.controller;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class BeanTest implements BeanNameAware , BeanFactoryAware, InitializingBean, DisposableBean {
private String name;
public void setName(String name) {
System.out.println("BeanTest setName() ..");
this.name = name;
}
BeanTest() {
System.out.println("默认构造器! BeanTest()");
}
// 实现了BeanNameAware 接口,回调该方法
@Override
public void setBeanName(String name) {
System.out.println("BeanNameAware.setBeanName() = " + name);
}
// 实现了 BeanFactoryAware ,回调该方法
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
System.out.println("BeanFactoryAware.setBeanFactory = " + beanFactory);
}
// 设置初始化方法
public void init() {
System.out.println("init .....");
}
public void destory() {
System.out.println("bean destory() ...");
}
// 实现 InitializingBean 接口,实例化bean 回调
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean.afterPropertiesSet() .....");
}
@PostConstruct
public void initPost() {
System.out.println("@PostConstruct ....");
}
@PreDestroy
public void preDestory() {
System.out.println("@PreDestroy ....");
}
// DisposableBean destroy
@Override
public void destroy() throws Exception {
System.out.println("DisposableBean.destroy() .....");
}
}
- MyBeanPostProcessor -> BeanPostProcessor Bean后置处理器
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
// BeanPostProcessor bean 初始化后 回调
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof BeanTest) {
System.out.println("postProcessAfterInitialization ...." + beanName);
}
return bean;
}
// BeanPostProcessor bean 初始化前 回调
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof BeanTest) {
System.out.println("postProcessBeforeInitialization ...." + beanName);
}
return bean;
}
}
- BeanTestConfig
@Configuration
public class BeanTestConfig {
// 指定 initMethod 和 destroyMethod
@Bean(initMethod = "init",destroyMethod = "destory")
public BeanTest beanTest() {
return new BeanTest();
}
}
- 运行结果:调用顺序
默认构造器! BeanTest()
BeanNameAware.setBeanName() = beanTest
BeanFactoryAware.setBeanFactory = org.springframework.beans.factory.support.DefaultListableBeanFactory@5b367418: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,cloudCustomerApplication,org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory,beanTestConfig,discoveryClientApi,helloController,myBeanPostProcessor,restTemplateDemo,IUserApiFallbackFactory,beanTest,restTemplate,com.example.cloudapi.config.Config,default.com.example.cloudcustomer.CloudCustomerApplication.FeignClientSpecification,server-provider.FeignClientSpecification,com.example.cloudapi.api.IUserApi,org.springframework.boot.autoconfigure.AutoConfigurationPackages,org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,org.springframework.boot.autoconfigure.condition.BeanTypeRegistry,propertySourcesPlaceholderConfigurer,org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration$TomcatWebSocketConfiguration,websocketServletWebServerCustomizer,org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryConfiguration$EmbeddedTomcat,tomcatServletWebServerFactory,org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,servletWebServerFactoryCustomizer,tomcatServletWebServerFactoryCustomizer,server-org.springframework.boot.autoconfigure.web.ServerProperties,org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor,org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata,webServerFactoryCustomizerBeanPostProcessor,errorPageRegistrarBeanPostProcessor,org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletConfiguration,dispatcherServlet,spring.http-org.springframework.boot.autoconfigure.http.HttpProperties,spring.mvc-org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties,org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration$DispatcherServletRegistrationConfiguration,dispatcherServletRegistration,org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration$PropagateEventsConfiguration,org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration,configurableEnvironmentConfiguration,org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,taskExecutorBuilder,applicationTaskExecutor,spring.task.execution-org.springframework.boot.autoconfigure.task.TaskExecutionProperties,org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,defaultValidator,methodValidationPostProcessor,org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration,error,beanNameViewResolver,org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration,conventionErrorViewResolver,org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,errorAttributes,basicErrorController,errorPageCustomizer,preserveErrorControllerTargetClassPostProcessor,spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties,org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter$FaviconConfiguration,faviconHandlerMapping,faviconRequestHandler,org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration,requestMappingHandlerAdapter,requestMappingHandlerMapping,mvcConversionService,mvcValidator,mvcContentNegotiationManager,mvcPathMatcher,mvcUrlPathHelper,viewControllerHandlerMapping,beanNameHandlerMapping,resourceHandlerMapping,mvcResourceUrlProvider,defaultServletHandlerMapping,mvcUriComponentsContributor,httpRequestHandlerAdapter,simpleControllerHandlerAdapter,handlerExceptionResolver,mvcViewResolver,mvcHandlerMappingIntrospector,org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter,defaultViewResolver,viewResolver,welcomePageHandlerMapping,requestContextFilter,org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,hiddenHttpMethodFilter,formContentFilter,org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,mbeanExporter,objectNamingStrategy,mbeanServer,org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,springApplicationAdminRegistrar,org.springframework.boot.autoconfigure.aop.AopAutoConfiguration$CglibAutoProxyConfiguration,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,org.springframework.cloud.autoconfigure.RefreshAutoConfiguration$RefreshScopeBeanDefinitionEnhancer,org.springframework.cloud.autoconfigure.RefreshAutoConfiguration,refreshScope,loggingRebinder,contextRefresher,refreshEventListener,org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,gsonBuilder,gson,standardGsonBuilderCustomizer,spring.gson-org.springframework.boot.autoconfigure.gson.GsonProperties,org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$Jackson2ObjectMapperBuilderCustomizerConfiguration,standardJacksonObjectMapperBuilderCustomizer,spring.jackson-org.springframework.boot.autoconfigure.jackson.JacksonProperties,org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperBuilderConfiguration,jacksonObjectMapperBuilder,org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$ParameterNamesModuleConfiguration,parameterNamesModule,org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration$JacksonObjectMapperConfiguration,jacksonObjectMapper,org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,jsonComponentModule,org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration,stringHttpMessageConverter,org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration$MappingJackson2HttpMessageConverterConfiguration,mappingJackson2HttpMessageConverter,org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration,org.springframework.boot.autoconfigure.http.GsonHttpMessageConvertersConfiguration,org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,messageConverters,org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration$LoggingCodecConfiguration,loggingCodecCustomizer,org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration$JacksonCodecConfiguration,jacksonCodecCustomizer,org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties,org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,taskSchedulerBuilder,spring.task.scheduling-org.springframework.boot.autoconfigure.task.TaskSchedulingProperties,org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,restTemplateBuilder,org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration$TomcatWebServerFactoryCustomizerConfiguration,tomcatWebServerFactoryCustomizer,org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,characterEncodingFilter,localeCharsetMappingsCustomizer,org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,multipartConfigElement,multipartResolver,spring.servlet.multipart-org.springframework.boot.autoconfigure.web.servlet.MultipartProperties,org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration,configurationPropertiesBeans,configurationPropertiesRebinder,org.springframework.cloud.autoconfigure.LifecycleMvcEndpointAutoConfiguration,environmentManager,org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration$EurekaClientConfigurationRefresher,org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration,eurekaDiscoverClientMarker,org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration,spring.cloud.service-registry.auto-registration-org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties,org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration,org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration$RefreshableEurekaClientConfiguration,scopedTarget.eurekaClient,eurekaClient,scopedTarget.eurekaApplicationInfoManager,eurekaApplicationInfoManager,scopedTarget.eurekaRegistration,eurekaRegistration,org.springframework.cloud.netflix.eureka.config.DiscoveryClientOptionalArgsConfiguration,discoveryClientOptionalArgs,org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration,eurekaFeature,eurekaClientConfigBean,serviceManagementMetadataProvider,eurekaInstanceConfigBean,discoveryClient,eurekaServiceRegistry,eurekaAutoServiceRegistration,org.springframework.cloud.client.CommonsClientAutoConfiguration,org.springframework.cloud.client.discovery.composite.CompositeDiscoveryClientAutoConfiguration,compositeDiscoveryClient,org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration,simpleDiscoveryProperties,simpleDiscoveryClient,org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration,ribbonFeature,springClientFactory,loadBalancerClient,propertiesFactory,default.org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration.RibbonClientSpecification,ribbon.eager-load-org.springframework.cloud.netflix.ribbon.RibbonEagerLoadProperties,ribbon-org.springframework.cloud.netflix.ribbon.ServerIntrospectorProperties,org.springframework.cloud.client.loadbalancer.AsyncLoadBalancerAutoConfiguration$LoadBalancerInterceptorConfig,asyncLoadBalancerInterceptor,asyncRestTemplateCustomizer,org.springframework.cloud.client.loadbalancer.AsyncLoadBalancerAutoConfiguration$AsyncRestTemplateCustomizerConfig,loadBalancedAsyncRestTemplateInitializer,org.springframework.cloud.client.loadbalancer.AsyncLoadBalancerAutoConfiguration,org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration$LoadBalancerInterceptorConfig,ribbonInterceptor,restTemplateCustomizer,org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration,loadBalancedRestTemplateInitializerDeprecated,loadBalancerRequestFactory,spring.cloud.loadbalancer.retry-org.springframework.cloud.client.loadbalancer.LoadBalancerRetryProperties,org.springframework.cloud.client.serviceregistry.ServiceRegistryAutoConfiguration,org.springframework.cloud.commons.httpclient.HttpClientConfiguration$ApacheHttpClientConfiguration,connManFactory,apacheHttpClientBuilder,apacheHttpClientFactory,org.springframework.cloud.commons.httpclient.HttpClientConfiguration,org.springframework.cloud.commons.util.UtilAutoConfiguration,inetUtilsProperties,inetUtils,org.springframework.cloud.configuration.CompatibilityVerifierAutoConfiguration,compositeCompatibilityVerifier,springBootVersionVerifier,spring.cloud.compatibility-verifier-org.springframework.cloud.configuration.CompatibilityVerifierProperties,org.springframework.cloud.netflix.ribbon.eureka.RibbonEurekaAutoConfiguration,default.org.springframework.cloud.netflix.ribbon.eureka.RibbonEurekaAutoConfiguration.RibbonClientSpecification,org.springframework.cloud.openfeign.ribbon.DefaultFeignLoadBalancedConfiguration,feignClient,org.springframework.cloud.openfeign.ribbon.FeignRibbonClientAutoConfiguration,cachingLBClientFactory,feignRequestOptions,feign.httpclient-org.springframework.cloud.openfeign.support.FeignHttpClientProperties,org.springframework.cloud.openfeign.FeignAutoConfiguration$HystrixFeignTargeterConfiguration,feignTargeter,org.springframework.cloud.openfeign.FeignAutoConfiguration,feignFeature,feignContext,feign.client-org.springframework.cloud.openfeign.FeignClientProperties]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@385e9564
postProcessBeforeInitialization ....beanTest
@PostConstruct ....
InitializingBean.afterPropertiesSet() .....
init .....
postProcessAfterInitialization ....beanTest
----容器关闭后
@PreDestroy ....
DisposableBean.destroy() .....
bean destory() ...