首页 > 解决方案 > spring boot应用使用jar打包时如何使用SpringBootServletInitializer

问题描述

我的 Spring Boot 应用程序中有一个类,它扩展了 SpringBootServletInitializer,在这个类中,我在运行时加载了 spring 数据源详细信息,当我将应用程序打包为 WAR 但将其更改为 jar 时,它工作正常,SpringBootServletInitializer 被忽略。并且从文档中发现 SpringBootServletInitializer 仅在我们将应用程序作为 WAR 运行时才被调用。

将spring boot应用程序作为jar运行时是否有等价物,我想通过从secrets中提取db详细信息在运行时设置spring数据源详细信息。

这就是我在扩展 SpringBootServletInitializer 的类中所做的

@Override
public void onStartup(ServletContext servletContext) throws ServletException 
....

servletContext.setInitParameter("spring.datasource.driver-class-name", dbClassName);
servletContext.setInitParameter("spring.datasource.url", dbURL);
servletContext.setInitParameter("spring.datasource.username", dbUserName);
servletContext.setInitParameter("spring.datasource.password", dbPWD);

标签: javaspringspring-boot

解决方案


您可以使用带有回调 run() 方法的接口之类的东西CommanLineRunner,该方法可以在 Spring 应用程序上下文实例化后在应用程序启动时调用,如下所示:

@Component
public class CommandLineAppStartupRunner implements CommandLineRunner,ServletContextAware {
    private static final Logger LOG =
      LoggerFactory.getLogger(CommandLineAppStartupRunner.class);
 
    private ServletContext context;

    @Override
    public void run(String...args) throws Exception {
        //provide what you want here
        LOG.info("This is triggered");
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
       this.context = servletContext;
    }
}

推荐阅读