• 20220510 Core Features 1. SpringApplication


    前言

    文档地址

    SpringApplication 类提供了一种方便的方法来引导从 main() 方法启动的 Spring 应用程序。在许多情况下,您可以委托给静态 SpringApplication.run 方法,如下例所示:

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class MyApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MyApplication.class, args);
        }
    
    }
    

    当您的应用程序启动时,您应该会看到类似于以下输出的内容:

      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::   v2.6.7
    
    2021-02-03 10:33:25.224  INFO 17321 --- [           main] o.s.b.d.s.s.SpringApplicationExample    : Starting SpringApplicationExample using Java 1.8.0_232 on mycomputer with PID 17321 (/apps/myjar.jar started by pwebb)
    2021-02-03 10:33:25.226  INFO 17900 --- [           main] o.s.b.d.s.s.SpringApplicationExample    : No active profile set, falling back to default profiles: default
    2021-02-03 10:33:26.046  INFO 17321 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
    2021-02-03 10:33:26.054  INFO 17900 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2021-02-03 10:33:26.055  INFO 17900 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.41]
    2021-02-03 10:33:26.097  INFO 17900 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2021-02-03 10:33:26.097  INFO 17900 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 821 ms
    2021-02-03 10:33:26.144  INFO 17900 --- [           main] s.tomcat.SampleTomcatApplication         : ServletContext initialized
    2021-02-03 10:33:26.376  INFO 17900 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
    2021-02-03 10:33:26.384  INFO 17900 --- [           main] o.s.b.d.s.s.SpringApplicationExample    : Started SampleTomcatApplication in 1.514 seconds (JVM running for 1.823)
    

    默认情况下,会显示 INFO 日志消息,包括一些相关的启动详细信息,例如启动应用程序的用户。如果您需要除 INFO 之外的日志级别,您可以设置,如 日志级别 中所述。应用程序版本是使用主应用程序类包中的实现版本确定的。设置 spring.main.log-startup-infofalse 可以关闭启动信息记录。这也将关闭应用程序激活 profile 的日志记录。

    要在启动期间添加额外的日志记录,您可以在 SpringApplication 子类中重写 logStartupInfo(boolean)

    1.1. 启动失败

    如果您的应用程序无法启动,注册 FailureAnalyzers 将有机会提供专门的错误消息和解决问题的具体措施。例如,如果您在 8080 端口上启动 Web 应用程序并且该端口已在使用中,您应该会看到类似于以下消息的内容:

    ***************************
    APPLICATION FAILED TO START
    ***************************
    
    Description:
    
    Embedded servlet container failed to start. Port 8080 was already in use.
    
    Action:
    
    Identify and stop the process that is listening on port 8080 or configure this application to listen on another port.
    

    Spring Boot 提供了许多FailureAnalyzer实现,并且您可以 添加自己的

    如果没有故障分析器能够处理异常,您仍然可以显示完整的条件报告以更好地了解问题所在。为此,您需要 启用 debug 属性启用 DEBUG 级别 记录 org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener

    例如,如果您使用 java -jar 运行应用程序,则可以按如下方式启用 debug 属性:

    $ java -jar myproject-0.0.1-SNAPSHOT.jar --debug
    

    1.2. 延迟初始化(懒加载)

    SpringApplication 允许延迟初始化应用程序。启用延迟初始化后,将根据需要创建 bean ,而不是在应用程序启动期间创建 bean 。因此,启用延迟初始化可以减少应用程序启动所需的时间。在 Web 应用程序中,启用延迟初始化将导致许多与 Web 相关的 bean 在收到 HTTP 请求之前不会被初始化。

    延迟初始化的一个缺点是它会延迟应用程序问题的发现。如果配置错误的 bean 被延迟初始化,则在启动期间将不再发生故障,并且只有在 bean 初始化时问题才会变得明显。还必须注意确保 JVM 有足够的内存来容纳应用程序的所有 bean,而不仅仅是那些在启动期间初始化的 bean。由于这些原因,默认情况下不启用延迟初始化,建议在启用延迟初始化之前对 JVM 的堆大小进行微调。

    可以使用 SpringApplicationBuilderlazyInitialization 方法或 SpringApplicationsetLazyInitialization 方法以编程方式启用延迟初始化 。或者,可以使用以下示例中所示的 spring.main.lazy-initialization 属性启用它:

    spring.main.lazy-initialization=true
    

    如果您想禁用某些 bean 的延迟初始化,同时对应用程序的其余部分使用延迟初始化,您可以使用 @Lazy(false) 注解将它们的延迟属性显式设置为 false

    1.3. 定制横幅(Banner)

    可以通过将 banner.txt 文件添加到类路径或将 spring.banner.location 属性设置为此类文件的位置来更改启动时打印的横幅。如果文件的编码不是 UTF-8 ,您可以设置 spring.banner.charset 。除了文本文件之外,您还可以将 banner.gifbanner.jpgbanner.png 图像文件添加到类路径或设置 spring.banner.image.location 属性。图像被转换为 ASCII 艺术表示并打印在任何文本横幅上方。

    在您的 banner.txt 文件中,您可以使用任何 Environment 里可用的键以及以下任何占位符:

    Banner variables

    变量 描述
    ${application.version} 应用程序的版本号,如 MANIFEST.MF 中所述。例如,Implementation-Version: 1.0 被打印为 1.0
    ${application.formatted-version} 应用程序的版本号,如 MANIFEST.MF 中所述,并进行了格式显示(用括号括起来,并带有前缀 v )。例如 (v1.0)
    ${spring-boot.version} 正在使用的 Spring Boot 版本。例如 2.2.0.RELEASE
    ${spring-boot.formatted-version} 正在使用的 Spring Boot 版本,其格式用于显示(用括号括起来,并带有前缀 v )。例如 (v2.2.0.RELEASE)
    ${Ansi.NAME}(或 ${AnsiColor.NAME}${AnsiBackground.NAME}${AnsiStyle.NAME} NAME 是指 ANSI 转义代码的名称。有关详细信息,请参见 AnsiPropertySource
    ${application.title} 您的应用程序的标题,如 MANIFEST.MF 中所述。例如 Implementation-Title: MyApp 被打印为 MyApp

    如果您想以编程方式生成横幅,可以使用 SpringApplication.setBanner(…) 方法。使用 org.springframework.boot.Banner 接口并实现自己的 printBanner() 方法。

    您还可以使用 spring.main.banner-mode 属性来确定是否必须在 System.out ( console ) 上打印横幅、发送到配置的记录器 ( log ) 或根本不生成 ( off )。

    打印的横幅以名称 springBootBanner 注册为单例 bean

    ${application.version}${application.formatted-version} 属性仅在您使用 Spring Boot 启动器时可用。如果您正在运行非解压 jar 并以 java -cp <classpath> <mainclass> 启动,不会解析这两个属性

    这就是为什么我们建议您始终使用 java org.springframework.boot.loader.JarLauncher 启动非解压 jar 。这将在构建类路径和启动应用程序之前初始化横幅变量 application.*

    1.4. 自定义 SpringApplication

    如果 SpringApplication 默认值不符合您的口味,您可以改为创建本地实例并对其进行自定义。例如,要关闭横幅,您可以编写:

    import org.springframework.boot.Banner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class MyApplication {
    
        public static void main(String[] args) {
            SpringApplication application = new SpringApplication(MyApplication.class);
            application.setBannerMode(Banner.Mode.OFF);
            application.run(args);
        }
    
    }
    

    传递给 SpringApplication 构造函数的参数是 Spring bean 的配置源。在大多数情况下,这些是对 @Configuration 类的引用,,但它们也可以是直接引用 @Component

    也可以通过使用 application.properties 文件来配置 SpringApplication 。有关详细信息,请参阅 外部化配置

    有关配置选项的完整列表,请参阅 SpringApplication

    1.5. 流式构建器(Builder) API

    如果您需要构建 ApplicationContext 层次结构(具有父/子关系的多个上下文),或者如果您更喜欢使用流式构建器 API,则可以使用 SpringApplicationBuilder

    SpringApplicationBuilder 允许您链接多个方法调用,并且包含允许您创建层次结构的 parent 以及 child 方法,如以下示例所示:

    new SpringApplicationBuilder()
            .sources(Parent.class)
            .child(Application.class)
            .bannerMode(Banner.Mode.OFF)
            .run(args);
    

    创建 ApplicationContext 层次结构时有一些限制。例如,Web 组件 必须 包含在子上下文中,并且相同 Environment 用于父上下文和子上下文。有关完整的详细信息,请参阅 SpringApplicationBuilder

    1.6. 应用程序可用性

    当部署在平台上时,应用程序可以使用 Kubernetes Probes 等基础设施向平台提供有关其可用性的信息。Spring Boot 包括对常用 livenessreadiness 可用性状态的开箱即用支持。如果您使用 Spring Boot 的 actuator 支持,那么这些状态将作为 health 端点组公开。

    此外,您还可以通过将 ApplicationAvailability 接口注入到自己的 bean 中来获取可用性状态。

    1.6.1. Liveness 状态

    应用程序的 Liveness 状态表明其内部状态是否允许其正常工作,或者如果当前失败则自行恢复。损坏(broken)的 Liveness 状态意味着应用程序处于无法恢复的状态,基础设施应重新启动应用程序。

    一般来说,Liveness 状态不应基于外部检查,例如 Health 检查 。如果是这样,一个失败的外部系统(数据库、Web API、外部缓存)将触发大规模重启和跨平台的级联故障。

    Spring Boot 应用程序的内部状态主要由 Spring ApplicationContext 表示。如果应用上下文已成功启动,Spring Boot 假定应用程序处于有效状态。一旦上下文被刷新,应用程序就被认为是活动的,请参阅 Spring Boot 应用程序生命周期和相关的应用程序事件

    1.6.2. Readiness 状态

    应用程序的 Readiness 状态表明应用程序是否已准备好处理流量。失败的 Readiness 状态告诉平台它现在不应该将流量路由到应用程序。这通常发生在启动期间、当 CommandLineRunnerApplicationRunner 组件被处理后,或者在应用程序决定它太忙而无法获得额外流量的任何时候。

    一旦调用了应用程序和命令行运行器,就认为应用程序已准备就绪,请参阅 Spring Boot 应用程序生命周期和相关的应用程序事件

    预期在启动期间运行的任务应该由 CommandLineRunnerApplicationRunner 组件执行,而不是使用 Spring 组件生命周期回调,例如 @PostConstruct

    1.6.3. 管理应用程序可用性状态

    应用程序组件可以随时检索当前的可用性状态,方法是注入 ApplicationAvailability 接口并在其上调用方法。更多时候,应用程序会想要监听状态更新或更新应用程序的状态。

    例如,我们可以将应用程序的 Readiness 状态导出到一个文件中,以便 Kubernetes “exec Probe” 可以查看这个文件:

    @Component
    public class MyReadinessStateExporter {
    
        @EventListener
        public void onStateChange(AvailabilityChangeEvent<ReadinessState> event) {
            switch (event.getState()) {
            case ACCEPTING_TRAFFIC:
                // create file /tmp/healthy
                break;
            case REFUSING_TRAFFIC:
                // remove file /tmp/healthy
                break;
            }
        }
    
    }
    

    我们还可以在应用中断且无法恢复时更新应用的状态:

    @Component
    public class MyLocalCacheVerifier {
    
        private final ApplicationEventPublisher eventPublisher;
    
        public MyLocalCacheVerifier(ApplicationEventPublisher eventPublisher) {
            this.eventPublisher = eventPublisher;
        }
    
        public void checkLocalCache() {
            try {
                // ...
            }
            catch (CacheCompletelyBrokenException ex) {
                AvailabilityChangeEvent.publish(this.eventPublisher, ex, LivenessState.BROKEN);
            }
        }
    
    }
    

    Spring Boot 通过 Actuator Health Endpoints 为 “Liveness” 和 “Readiness” 提供 Kubernetes HTTP 探测。您可以 在专用部分中获得有关在 Kubernetes 上部署 Spring Boot 应用程序的 更多指导。

    1.7. 应用程序事件和监听器

    除了常见的 Spring Framework 事件,例如 ContextRefreshedEventSpringApplication 还发送一些额外的应用程序事件。

    有些事件实际上是在创建 ApplicationContext 之前触发的,因此您无法将监听器注册为 @Bean 来监听事件。您可以使用 SpringApplication.addListeners(...) 方法或 SpringApplicationBuilder.listeners(...) 方法注册它们。

    如果您希望这些监听器自动注册,而不管创建应用程序的方式如何,可以将 META-INF/spring.factories 文件添加到项目中,并使用 org.springframework.context.ApplicationListener 键引用您的监听器,如以下示例所示:

    org.springframework.context.ApplicationListener=com.example.project.MyListener
    

    当您的应用程序运行时,应用程序事件按以下顺序发送(参考 org.springframework.boot.SpringApplication#run(java.lang.String...) ):

    1. 在运行开始时,进行任何处理之前(监听器和初始化器 (initializers) 的注册除外),发送 ApplicationStartingEvent

      listeners.starting(bootstrapContext, this.mainApplicationClass);
      
    2. Environment 将被发送到已知的上下文中使用,但是在创建上下文之前,发送 ApplicationEnvironmentPreparedEvent

      ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
      
      listeners.environmentPrepared(bootstrapContext, environment);
      
    3. ApplicationContext 被准备好且调用 ApplicationContextInitializers 之后,但未加载任何 bean 定义之前,发送 ApplicationContextInitializedEvent

      prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
      
      listeners.contextPrepared(context);
      
    4. 在刷新开始之前,但在加载bean定义之后,发送 ApplicationPreparedEvent

      prepareContext(context, environment, listeners, applicationArguments, printedBanner);
      
      listeners.contextLoaded(context);
      
    5. 在上下文已被刷新后,但在 application runnerscommand-line runners 被调用前,发送 ApplicationStartedEvent

      listeners.started(context, timeTakenToStartup);
      
    6. LivenessState.CORRECT 之后,立即发送 AvailabilityChangeEvent ,表明应用程序被认为是活跃的

      listeners.started(context, timeTakenToStartup);
      
    7. application runnerscommand-line runners 被调用后,发送 ApplicationReadyEvent 。它指示该应用程序已准备就绪,可以处理请求

      listeners.ready(context, timeTakenToReady);
      
    8. ReadinessState.ACCEPTING_TRAFFIC 之后,立即发送 AvailabilityChangeEvent ,表示应用程序已准备好为请求提供服务

      listeners.ready(context, timeTakenToReady);
      
    9. 在启动异常时,发送 ApplicationFailedEvent

      handleRunFailure(context, ex, exceptionReporters, listeners);
      
      listeners.failed(context, exception);
      

    上面的列表仅包括与 SpringApplication 绑定的 SpringApplicationEvent 。除此之外,在 ApplicationPreparedEvent 之后以及 ApplicationStartedEvent 之前,还发布了以下事件:

    • 在 WebServer 准备就绪后发送 WebServerInitializedEventServletWebServerInitializedEventReactiveWebServerInitializedEvent 分别是 servlet 和响应式 servlet 的变种

    • ApplicationContext 被刷新后发送 ContextRefreshedEvent

      finishRefresh();
      
      publishEvent(new ContextRefreshedEvent(this));
      

    您通常不需要使用应用程序事件,但知道它们的存在会很方便。在内部,Spring Boot 使用事件来处理各种任务。

    默认情况下,事件监听器不应运行可能冗长的任务,因为它们在同一线程中执行。考虑改用 应用程序和命令行运行器

    应用程序事件是通过使用 Spring Framework 的事件发布机制发送的。此机制的一部分确保在子级上下文中发布给监听器的事件也会在任何祖先上下文中发布给监听器。因此,如果您的应用程序使用 SpringApplication 实例的层次结构,则监听器可能会收到同一类型的应用程序事件的多个实例。

    为了使您的监听器能够区分自身上下文的事件和后代上下文的事件,它应注入自身的应用上下文,然后将注入的上下文与事件的上下文进行比较。可以通过实现 ApplicationContextAware 来注入上下文,或者,如果监听器是 bean ,则可以使用 @Autowired 注入上下文。

    1.8. Web Environment

    SpringApplication 试图创建正确类型的 ApplicationContext 。确定 WebApplicationType 的算法非常简单:

    • 如果存在 Spring MVC ,则使用 AnnotationConfigServletWebServerApplicationContext
    • 如果不存在 Spring MVC 且存在 Spring WebFlux ,则使用 AnnotationConfigReactiveWebServerApplicationContext
    • 否则,使用 AnnotationConfigApplicationContext

    这意味着如果您在同一个应用程序中使用 Spring MVC 和来自 Spring WebFlux 的 WebClient ,则默认情况下将使用 Spring MVC 。您可以通过调用 setWebApplicationType(WebApplicationType) 轻松覆盖它。

    也可以通过调用 setApplicationContextClass(…) 来完全控制使用的 ApplicationContext 类型。

    在 JUnit 测试中使用 SpringApplication 时,通常需要调用 setWebApplicationType(WebApplicationType.NONE)

    参考源码:

    org.springframework.boot.SpringApplication#run(java.lang.String...)
        context = createApplicationContext();
    
    
    org.springframework.boot.SpringApplication#SpringApplication(org.springframework.core.io.ResourceLoader, java.lang.Class<?>...)
        this.webApplicationType = WebApplicationType.deduceFromClasspath();
    

    1.9. 访问应用程序参数

    如果您需要访问传递给 SpringApplication.run(...) 的应用程序参数,则可以注入 org.springframework.boot.ApplicationArgumentsApplicationArguments 接口提供对原始 String[] 参数以及已解析 optionnon-option 参数的访问,如以下示例所示:

    import java.util.List;
    
    import org.springframework.boot.ApplicationArguments;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MyBean {
    
        public MyBean(ApplicationArguments args) {
            boolean debug = args.containsOption("debug");
            List<String> files = args.getNonOptionArgs();
            if (debug) {
                System.out.println(files);
            }
            // if run with "--debug logfile.txt" prints ["logfile.txt"]
        }
    
    }
    

    Spring Boot 也向 Spring Environment 注册了一个 CommandLinePropertySource 。这样,您还可以使用 @Value 注解注入单个应用程序参数

    1.10. 使用 ApplicationRunnerCommandLineRunner

    如果启动 SpringApplication 后需要运行一些特定的代码,则可以实现 ApplicationRunnerCommandLineRunner 接口。这两个接口以相同的方式工作,并提供单一的 run 方法,该方法在 SpringApplication.run(...) 完成之前就被调用。

    这个约定非常适合应该在 应用程序启动之后 但 开始接受流量之前 运行的任务。

    CommandLineRunner 接口以字符串数组的形式提供对应用程序参数的访问,而 ApplicationRunner 使用前面讨论的 ApplicationArguments 接口。以下示例显示了一个带有 run 方法的 CommandLineRunner

    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MyCommandLineRunner implements CommandLineRunner {
    
        @Override
        public void run(String... args) {
            // Do something...
        }
    
    }
    

    如果定义了必须按特定顺序调用的多个 CommandLineRunnerApplicationRunner bean,则可以另外实现 org.springframework.core.Ordered 接口或使用 org.springframework.core.annotation.Order 注解。

    参考源码:

    org.springframework.boot.SpringApplication#run(java.lang.String...)
        callRunners(context, applicationArguments);
    

    Runner 执行时不是异步调用,而是在 ApplicationStartedEvent 事件和 ApplicationReadyEvent 之间执行。

    ApplicationRunnerCommandLineRunner 接口的不同之处在于 run 方法入参不同,前者是 ApplicationArguments ,后者是String...

    如果有多个 Runner ,需要指定执行顺序时,可以实现 org.springframework.core.Ordered 接口或使用 @org.springframework.core.annotation.Order 注解。

    1.11. Application Exit

    每个 SpringApplication 都向 JVM 注册一个关闭钩子,以确保 ApplicationContext 在退出时优雅地关闭。可以使用所有标准的 Spring 生命周期回调(例如 DisposableBean 接口或 @PreDestroy 注解)。

    如果希望在 SpringApplication.exit() 被调用时返回特定的退出代码,则可以让 bean 实现 org.springframework.boot.ExitCodeGenerator 接口。然后可以将此退出代码传递给 System.exit() ,以将其作为状态代码返回。

    import org.springframework.boot.ExitCodeGenerator;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    
    @SpringBootApplication
    public class MyApplication {
    
        @Bean
        public ExitCodeGenerator exitCodeGenerator() {
            return () -> 42;
        }
    
        public static void main(String[] args) {
            System.exit(SpringApplication.exit(SpringApplication.run(MyApplication.class, args)));
        }
    
    }
    

    此外,异常 Exception 实现 ExitCodeGenerator 接口后,当抛出异常时,Spring Boot 返回由实现的 getExitCode() 方法提供的退出代码。

    直接停止虚拟机不能返回特定的退出代码。

    1.12. Admin Features

    通过指定 spring.application.admin.enabled 属性,可以为应用程序启用与管理(admin)相关的功能。这将在平台 MBeanServer 上公开 SpringApplicationAdminMXBean 。您可以使用此功能来远程管理 Spring Boot 应用程序。此功能也可用于任何服务包装器实现。

    如果您想知道应用程序在哪个 HTTP 端口上运行,通过 local.server.port 属性获取

    1.13. Application Startup tracking

    在应用启动期间,SpringApplicationApplicationContext 执行许多与应用生命周期、bean 生命周期甚至处理应用事件相关的任务。有了 ApplicationStartup ,Spring Framework 允许您使用 StartupStep 对象 跟踪应用的启动顺序。可以出于分析目的收集这些数据,或者只是为了更好地了解应用启动过程。

    您可以在设置 SpringApplication 实例时选择 ApplicationStartup 实现。例如,要使用 BufferingApplicationStartup

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
    
    @SpringBootApplication
    public class MyApplication {
    
        public static void main(String[] args) {
            SpringApplication application = new SpringApplication(MyApplication.class);
            application.setApplicationStartup(new BufferingApplicationStartup(2048));
            application.run(args);
        }
    
    }
    

    第一个可用的实现 FlightRecorderApplicationStartup 由 Spring Framework 提供。它将 Spring 特定的启动事件添加到 Java Flight Recorder 会话中,用于分析应用程序并将它们的 Spring 上下文生命周期与 JVM 事件(例如 allocations 、GC、类加载……)相关联。配置完成后,您可以通过运行启用了 Flight Recorder 的应用程序来记录数据:

    $ java -XX:StartFlightRecording:filename=recording.jfr,duration=10s -jar demo.jar
    

    Spring Boot 附带 BufferingApplicationStartup 变体;此实现旨在缓冲启动步骤并将它们排入外部度量系统。应用程序可以在任何组件中请求 BufferingApplicationStartup 类型的 bean 。

    Spring Boot 也可以配置为公开一个以 JSON 文档形式提供此信息的 startup 端点

    展示 Startup 启动信息

    1. pom.xml 里添加依赖

      <!-- web -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
      </dependency>
      
      <!-- actuator -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-actuator</artifactId>
      </dependency>
      
    2. application.properties 里增加配置

      management.endpoints.web.exposure.include=startup
      
    3. 启动类

      @SpringBootApplication
      public class StudySpringBootApplication {
      
          public static void main(String[] args) {
              SpringApplication application = new SpringApplication(StudySpringBootApplication.class);
              application.setApplicationStartup(new BufferingApplicationStartup(2048));
              application.run(args);
          }
      
      }
      
    4. 访问 http://localhost:8080/actuator/startup

  • 相关阅读:
    简单工厂设计模式
    MVC备忘
    在MVC后台代码中想实现删除时弹出"确认删除"效果
    集合
    嵌套
    整理 补课内容
    百鸡百钱
    ////输入一个100以内的数,判断是不是正整数;
    课后题 5 6
    课后题3,4
  • 原文地址:https://www.cnblogs.com/huangwenjie/p/16354157.html
Copyright © 2020-2023  润新知