【问题标题】:How to use SpringBootServletInitializer when using a jar packaging for spring boot applicationspring boot应用使用jar打包时如何使用SpringBootServletInitializer
【发布时间】:2020-11-06 20:11:05
【问题描述】:

我的 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);

【问题讨论】:

  • "我想在运行时通过从 secrets 中提取 db 详细信息来设置 spring 数据源详细信息。" - 你能解释一下或者举个例子吗?
  • 我将spring数据源属性设置为servlet上下文的代码sn-p,当我作为JAR运行时想要做同样的事情。现有代码仅在我将其作为 WAR 运行时才有效。
  • 你能告诉你从哪里得到 dbClassName 和其他变量吗?

标签: java spring spring-boot


【解决方案1】:

您可以使用类似 CommanLineRunner 接口的回调 run() 方法,该方法可以在 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;
    }
}

【讨论】:

    猜你喜欢
    • 2016-12-15
    • 2020-10-03
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    相关资源
    最近更新 更多