有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java最小化Spring启动时间

在我看来,SpringBoot项目需要很长时间才能加载。这可能是因为SpringBoot正在为您配置组件,其中一些组件您甚至不需要。 最明显的做法是从类路径中删除不必要的依赖项。然而,这还不够

有没有办法找出SpringBoot正在为您配置哪些模块,以找出您不需要的模块并禁用它们

一般来说,还有什么可以加快SpringBoot应用程序的启动时间的呢


共 (2) 个答案

  1. # 1 楼答案

    我可以告诉您,我运行了一个大型(800000多行代码)应用程序,通过SpringMVC、JMS、Atomikos事务、Hibernate、JMX支持和嵌入式Tomcat使用RESTfulWebServices。有了这些,应用程序将在大约19秒后在我的本地桌面上启动

    SpringBoot尽力不配置您不使用的模块。但是,很容易引入您不希望引入的其他依赖项和配置

    请记住,Spring Boot遵循约定优先于配置的范例,只需在类路径中放置一个库,就会导致Spring Boot尝试配置模块以使用库。此外,通过使用@RestController注释类这样简单的操作,将触发Spring引导以自动配置整个Spring MVC堆栈

    您可以在封面下看到正在发生的事情,并启用调试日志记录,只需在从命令行启动应用程序时指定 debug。您还可以在应用程序中指定debug=true。财产

    此外,您可以在application.properties中设置日志记录级别,如下所示:

    logging.level.org.springframework.web: DEBUG
    logging.level.org.hibernate: ERROR
    

    如果检测到不需要的自动配置模块,则可以将其禁用。可在此处找到此文档:http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#using-boot-disabling-specific-auto-configuration

    例如:

    @Configuration
    @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
    public class MyConfiguration {
    }
    
  2. # 2 楼答案

    一些可能有用的附加提示

    此外:

    正如this article建议对本地开发环境使用@ComponentScan(lazyInit = true)

    TL;博士

    What we want to achieve is to enable the bean lazy loading only in your local development environment and leave eager initialization for production. They say you can’t have your cake and eat it too, but with Spring you actually can. All thanks to profiles.

    @SpringBootApplication
    public class LazyApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(LazyApplication.class, args);
        }
    
        @Configuration
        @Profile("local")
        @ComponentScan(lazyInit = true)
        static class LocalConfig {
        }
    
    }