首页 > 编程语言 >Java-SpringBean的生命周期

Java-SpringBean的生命周期

时间:2023-12-12 13:33:08浏览次数:30  
标签:00 12 Java 22 08 SpringBean 生命周期 2023 5372

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\[email protected]\test-spring-cloud\eureka\target\classes started by ChengHaoQian in E:\CreateSoftBase\CVSKu\Git\Gitee\[email protected]\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

标签:00,12,Java,22,08,SpringBean,生命周期,2023,5372
From: https://www.cnblogs.com/anhaoyang/p/javaspringbean-s-life-cycle-1d4les.html

相关文章

  • Java开发者的Python快速实战指南:实用工具之PDF转DOCX文档(可视化界面)
    首先,大家对Python语法的了解已经基本完成,现在我们需要开始进行各种练习。我为大家准备了一些练习题目,比如之前的向量数据库等,这些题目可以参考第三方的SDK来进行操作,文档也是比较完善的。这个过程有点像我们之前使用Java对接第三方接口的方式,所以今天我想开发一个很实用的工具类,用......
  • Java开发者的Python快速实战指南:实用工具之PDF转DOCX文档(可视化界面)
    首先,大家对Python语法的了解已经基本完成,现在我们需要开始进行各种练习。我为大家准备了一些练习题目,比如之前的向量数据库等,这些题目可以参考第三方的SDK来进行操作,文档也是比较完善的。这个过程有点像我们之前使用Java对接第三方接口的方式,所以今天我想开发一个很实用的工具类,用......
  • Java数组
    免责声明:java基础资料均来自于韩顺平老师的《循序渐进学Java零基础》教案,具体视频内容可以去B站观看,这些资料仅用于学习交流,不得转载用于商业活动1.数组数组可用存放多个同一类型的数据,数组也是一种数据类型,是引用类型1.1一维数组1.1.1使用方式1-动态初始化语法:数据类型数......
  • JavaWeb——文件上传与下载
    一、文件上传简介1、文件上传的步骤(1)要有一个form表单,请求方式为post请求(因为上传的文件一般都超出长度限制)。(2)form标签的encType属性值必须为multipart/form-data。表示提交的数据,以多段的形式进行拼接,然后以二进制流的形式发送给服务器。多段:一个表单项代表一个数据......
  • JAVA 短剧小程序源码功能说明?如何运营?需要什么资质?
    JAVA短剧小程序源码的功能主要包含以下几个方面:1.用户登录注册:用户可以通过输入用户名和密码进行登录,或者通过注册账号来使用小程序。2.短剧浏览:用户可以在小程序中浏览各种类型的短剧,如喜剧、爱情剧、科幻剧等。同时,用户可以查看短剧的简介、演员信息以及播放量等。3.短剧搜......
  • JAVA 同城外卖到店跑腿团购多合一系统源码的技术方案
    随着互联网技术的不断发展,同城外卖、到店跑腿和团购业务逐渐成为人们日常生活中不可或缺的一部分。为了满足这一需求,我们设计并实现了一个基于JAVA技术的同城外卖到店跑腿团购多合一系统。本系统采用了先进的架构和算法,以提高系统的性能和可扩展性,并确保了数据的安全性和稳定性。一......
  • JAVA 短剧系统小程序开发的优势和好处
    随着互联网的普及和用户需求的多样化,小程序开发成为了一个备受关注的领域。其中,JAVA短剧系统小程序开发以其独特的优势和好处,逐渐在市场上占据了一席之地。本文将详细介绍JAVA短剧系统小程序开发的优势和好处,帮助读者更好地了解其价值和潜力。一、优势开源、免费JAVA短剧系统小程序......
  • JAVA同城服务货运搬家小程序系统源码的运营和优势
    随着城市化进程的加速和人口流动的增加,同城货运搬家服务逐渐成为人们生活中的重要需求。为了满足这一需求,我们开发了一款基于JAVA的同城服务货运搬家小程序系统。本系统具有用户友好的界面和高效稳定的系统性能,能够有效地连接货运服务提供者与需求者,实现货运服务的在线预约。本文将......
  • JAVA日期当天0点0分0秒
    LocalDateTimeLocalDateTimeldt=LocalDateTime.now();LocalDateTimetodayZero=LocalDateTime.of(ldt.getYear(),ldt.getMonthValue(),ldt.getDayOfMonth(),0,0,0);DateTimeFormatterDateTimeFormatterDATE_ZERO_FORMAT=DateTimeFormatter.ofPattern("......
  • spring bean的生命周期
    springbean的生命周期分为六个阶段阶段一:容器启动阶段主要完成了扫描、实例化beanDefinitino对象、注册BeanPostProcessor、验证beanDefinition是否合格阶段二:Bean的实例化阶段主要推断实例化方式、实例化对象阶段三:bean的属性注入提前暴露、循环依赖做支持、查找注入信息......