java - 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);
解决方案
您可以使用带有回调 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;
}
}
推荐阅读
- json - 如何将 JSON 编码对象作为字符串包含在另一个对象中,该对象也将被编码为字符串
- deep-learning - 在深度学习中执行批量标准化的确切逻辑是什么?
- wordpress - 在自定义帖子类型和用户之间创建关系
- azure-devops - 为什么 Azure DevOps Build Pipeline 无法下载源代码并出现错误?
- azure - 从 VSCode 或 Visual Studio 下载 Azure AD 自定义策略
- php - 我正在使用 Spatie\pdfToImage,当它必须制作缩略图时,网站会永远加载
- javascript - v13 中的成员角色?
- arrays - 如何将表单上的每个 PictureBox 加载到数组中?
- python - 为什么我不能遍历 selenium 中的列表?
- sharepoint - Microsoft Graph 为特定人员创建共享链接