Java-SpringBean的生命周期

Java-SpringBean的生命周期

简单版

  1. 实例化(Instantiation):

    • 当 Spring 容器启动时,它会检查配置文件或注解,然后实例化所有在配置中声明的 Bean。这是通过构造函数或工厂方法进行的。
  2. 属性设置(Population of Properties):

    • 容器实例化 Bean 后,会通过依赖注入或者setter方法将配置的属性注入到 Bean 中。
  3. 初始化前(Initialization):

    • 在实例被完全初始化之前,可以执行一些自定义的初始化操作。 @PostConstruct​ 注解来实现,或者配置 init-method​ 来实现。
  4. 初始化后(Initialization):

    • 在实例完全初始化之后,可以执行一些自定义的初始化操作。这可以通过实现 InitializingBean​ 接口的 afterPropertiesSet​ 方法。
  5. 使用中(In Use):

    • Bean 实例化且初始化完成后,容器将其交给应用程序使用。在这个阶段,Bean 执行它的业务逻辑。
  6. 销毁前(Destruction):

    • 当容器关闭时,或者手动从容器中移除 Bean 时,会执行销毁前的操作。这可以通过实现 DisposableBean​ 接口的 destroy​ 方法,使用 @PreDestroy​ 注解,或者配置 destroy-method​ 来实现。
  7. 销毁后(Destruction):

    • 在 Bean 销毁后,可以执行一些自定义的清理操作。这可以通过实现 DisposableBean​ 接口的 destroy​ 方法、使用 @PreDestroy​ 注解,或者配置 destroy-method​ 来实现。

详细版

image

package com.anhaoyang.test;

import jakarta.annotation.PostConstruct;
import jakarta.servlet.ServletContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

@Component
public class SpringBean implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware, EnvironmentAware, ResourceLoaderAware, ApplicationEventPublisherAware, MessageSourceAware, ApplicationContextAware, ServletContextAware, InitializingBean, DisposableBean {

    @Autowired
    public String stringBean;

    public SpringBean() {
        System.err.println("1. SpringBean " + stringBean);
    }

    @Override
    public void setBeanName(String name) {
        System.err.println("2. setBeanName, name=" + name);
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        System.err.println("3. setBeanClassLoader, classLoader=" + classLoader.getName());
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.err.println("4. setBeanFactory, beanFactory=" + beanFactory.getClass().getName());
    }

    @Override
    public void setEnvironment(Environment environment) {
        System.err.println("5. setEnvironment, environment=" + environment.getActiveProfiles());
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        System.err.println("6. setResourceLoader, resourceLoader=" + resourceLoader);
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        System.err.println("7. setApplicationEventPublisher, applicationEventPublisher=" + applicationEventPublisher.getClass().getName());
    }


    @Override
    public void setMessageSource(MessageSource messageSource) {
        System.err.println("8. setMessageSource, messageSource=" + messageSource.getClass().getName());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.err.println("9. setApplicationContext, applicationContext=" + applicationContext.getId());
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        //是web应用才会调用
        System.err.println("10. setServletContext, applicationContext=" + servletContext.getContextPath());
    }

    @PostConstruct
    public void init1() {
        System.err.println("11. @PostConstruct - 1 " + stringBean);
    }

    @PostConstruct
    public void init2() {
        System.err.println("11. @PostConstruct - 2 " + stringBean);
    }

    @PostConstruct
    public void init3() {
        System.err.println("11. @PostConstruct - 3 " + stringBean);
    }

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

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



  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =======<span style="font-weight: bold;" class="mark">|_|</span>============|___/=/_/_/_/
 :: Spring Boot ::                (v3.0.2)

2023-12-12T13:22:08.691+08:00  INFO 5372 --- [           main] com.anhaoyang.test.EurekaApplication     : Starting EurekaApplication using Java 17.0.9 with PID 5372 (E:\CreateSoftBase\CVSKu\Git\Gitee\anhaoyang@Gitee.com\test-spring-cloud\eureka\target\classes started by ChengHaoQian in E:\CreateSoftBase\CVSKu\Git\Gitee\anhaoyang@Gitee.com\test-spring-cloud)
2023-12-12T13:22:08.696+08:00  INFO 5372 --- [           main] com.anhaoyang.test.EurekaApplication     : No active profile set, falling back to 1 default profile: "default"
2023-12-12T13:22:10.164+08:00  INFO 5372 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=a4ffb4ab-32be-3d3d-9706-a765a3393ee5
2023-12-12T13:22:10.801+08:00  INFO 5372 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 21006 (http)
2023-12-12T13:22:10.813+08:00  INFO 5372 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-12-12T13:22:10.813+08:00  INFO 5372 --- [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.5]
2023-12-12T13:22:10.964+08:00  INFO 5372 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-12-12T13:22:10.975+08:00  INFO 5372 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2185 ms
2023-12-12T13:22:12.187+08:00  INFO 5372 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON encoding codec LegacyJacksonJson
2023-12-12T13:22:12.188+08:00  INFO 5372 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON decoding codec LegacyJacksonJson
2023-12-12T13:22:12.471+08:00  INFO 5372 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML encoding codec XStreamXml
2023-12-12T13:22:12.471+08:00  INFO 5372 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML decoding codec XStreamXml
1. SpringBean null
2. setBeanName, name=springBean
3. setBeanClassLoader, classLoader=app
4. setBeanFactory, beanFactory=org.springframework.beans.factory.support.DefaultListableBeanFactory
5. setEnvironment, environment=[Ljava.lang.String;@3d8bd881
6. setResourceLoader, resourceLoader=org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@609db546, started on Tue Dec 12 13:22:08 CST 2023
7. setApplicationEventPublisher, applicationEventPublisher=org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
8. setMessageSource, messageSource=org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
9. setApplicationContext, applicationContext=EUREKA-SERVER
10. @PostConstruct - 1 stringBean
10. @PostConstruct - 3 stringBean
10. @PostConstruct - 2 stringBean
11. afterPropertiesSet
2023-12-12T13:22:15.333+08:00  INFO 5372 --- [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2023-12-12T13:22:18.707+08:00  INFO 5372 --- [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2023-12-12T13:22:18.720+08:00  INFO 5372 --- [           main] DiscoveryClientOptionalArgsConfiguration : Eureka HTTP Client uses RestTemplate.
2023-12-12T13:22:18.782+08:00  WARN 5372 --- [           main] iguration$LoadBalancerCaffeineWarnLogger : Spring Cloud LoadBalancer is currently working with the default cache. While this cache implementation is useful for development and tests, it's recommended to use Caffeine cache in production.You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.
2023-12-12T13:22:18.814+08:00  INFO 5372 --- [           main] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING
2023-12-12T13:22:18.860+08:00  INFO 5372 --- [           main] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1
2023-12-12T13:22:18.861+08:00  INFO 5372 --- [           main] com.netflix.discovery.DiscoveryClient    : Client configured to neither register nor query for data.
2023-12-12T13:22:18.872+08:00  INFO 5372 --- [           main] com.netflix.discovery.DiscoveryClient    : Discovery Client initialized at timestamp 1702358538871 with initial instances count: 0
2023-12-12T13:22:18.931+08:00  INFO 5372 --- [           main] c.n.eureka.DefaultEurekaServerContext    : Initializing ...
2023-12-12T13:22:18.935+08:00  WARN 5372 --- [           main] c.n.eureka.cluster.PeerEurekaNodes       : The replica size seems to be empty. Check the route 53 DNS Registry
2023-12-12T13:22:19.021+08:00  INFO 5372 --- [           main] c.n.e.registry.AbstractInstanceRegistry  : Finished initializing remote region registries. All known remote regions: []
2023-12-12T13:22:19.022+08:00  INFO 5372 --- [           main] c.n.eureka.DefaultEurekaServerContext    : Initialized
2023-12-12T13:22:19.038+08:00  INFO 5372 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint(s) beneath base path '/actuator'
2023-12-12T13:22:19.103+08:00  INFO 5372 --- [           main] o.s.c.n.e.s.EurekaServiceRegistry        : Registering application EUREKA-SERVER with eureka with status UP
2023-12-12T13:22:19.122+08:00  INFO 5372 --- [       Thread-9] o.s.c.n.e.server.EurekaServerBootstrap   : isAws returned false
2023-12-12T13:22:19.123+08:00  INFO 5372 --- [       Thread-9] o.s.c.n.e.server.EurekaServerBootstrap   : Initialized server context
2023-12-12T13:22:19.123+08:00  INFO 5372 --- [       Thread-9] c.n.e.r.PeerAwareInstanceRegistryImpl    : Got 1 instances from neighboring DS node
2023-12-12T13:22:19.123+08:00  INFO 5372 --- [       Thread-9] c.n.e.r.PeerAwareInstanceRegistryImpl    : Renew threshold is: 1
2023-12-12T13:22:19.123+08:00  INFO 5372 --- [       Thread-9] c.n.e.r.PeerAwareInstanceRegistryImpl    : Changing status to UP
2023-12-12T13:22:19.138+08:00  INFO 5372 --- [       Thread-9] e.s.EurekaServerInitializerConfiguration : Started Eureka Server
2023-12-12T13:22:19.145+08:00  INFO 5372 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 21006 (http) with context path ''
2023-12-12T13:22:19.147+08:00  INFO 5372 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 21006
2023-12-12T13:22:21.627+08:00  INFO 5372 --- [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2023-12-12T13:22:21.643+08:00  INFO 5372 --- [           main] com.anhaoyang.test.EurekaApplication     : Started EurekaApplication in 15.794 seconds (process running for 16.451)
EurekaServer启动成功: http://127.0.0.1:21006
2023-12-12T13:22:23.428+08:00  INFO 5372 --- [ionShutdownHook] o.s.c.n.e.s.EurekaServiceRegistry        : Unregistering application EUREKA-SERVER with eureka with status DOWN
2023-12-12T13:22:23.505+08:00  INFO 5372 --- [ionShutdownHook] o.s.c.n.e.server.EurekaServerBootstrap   : Shutting down Eureka Server..
2023-12-12T13:22:23.510+08:00  INFO 5372 --- [ionShutdownHook] c.n.eureka.DefaultEurekaServerContext    : Shutting down ...
2023-12-12T13:22:23.542+08:00  INFO 5372 --- [ionShutdownHook] c.n.eureka.DefaultEurekaServerContext    : Shut down
2023-12-12T13:22:23.542+08:00  INFO 5372 --- [ionShutdownHook] o.s.c.n.e.server.EurekaServerBootstrap   : Eureka Service is now shutdown...
2023-12-12T13:22:23.543+08:00  INFO 5372 --- [ionShutdownHook] c.n.eureka.DefaultEurekaServerContext    : Shutting down ...
2023-12-12T13:22:23.551+08:00  INFO 5372 --- [ionShutdownHook] c.n.eureka.DefaultEurekaServerContext    : Shut down
2023-12-12T13:22:23.557+08:00  INFO 5372 --- [ionShutdownHook] com.netflix.discovery.DiscoveryClient    : Shutting down DiscoveryClient ...
2023-12-12T13:22:23.559+08:00  INFO 5372 --- [ionShutdownHook] com.netflix.discovery.DiscoveryClient    : Completed shut down of DiscoveryClient
12. destroy

进程已结束,退出代码130


参考

https://zhuanlan.zhihu.com/p/611618304?utm_id=0

posted @ 2023-12-12 13:29  安浩阳  阅读(157)  评论(0编辑  收藏  举报