我需要从 spring boot war 外部加载 application.properties 文件,该文件将部署在 tomcat 中。
\n\n我尝试了各种解决方案,缺少一些东西
\n\n尝试在Windows中设置环境变量如下
\n\n名称:SPRING_CONFIG_NAME\n值:D:/test/application.properties
我尝试了上述值的多个值,例如前缀中的 file:/// 和仅 file: 作为前缀。没有任何效果
\n\n尝试将上下文参数设置为 tomcat,如下所示,所以答案\n /sf/answers/3128806761/
尝试在扩展 SpringBootServletIntializer 的主文件中像这样加载
\n\nprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {\n return application.sources(Application.class)\n .properties(getProperties());\n }
\n\n public static void main(String[] args) throws Exception {\n SpringApplication.run(Application.class, args);\n\n SpringApplicationBuilder springApplicationBuilder = (SpringApplicationBuilder) (new SpringApplicationBuilder(Application.class))\n .sources(Application.class)\n .properties(getProperties())\n .run(args);\n\n\n }\n\n static Properties getProperties() {\n Properties props = new Properties();\n props.put("spring.config.location", "file:///D:/test/application.properties\xe2\x80\x8b");\n return props;\n }\nRun Code Online (Sandbox Code Playgroud)我不确定我错过了什么,请帮忙。
\nSpring Boot 中的外部配置
使用 Spring Boot 时,有记录的命名约定和目录结构。Spring Boot 应用程序会从优先列表中搜索要加载的属性,因此有一些建议供您考虑:
spring.config.location来定位要从中加载属性源的特定文件或目录。您可以使用它来指定要搜索的目录或要加载的单个文件。不过,如果您打算使用基于配置文件的属性,请谨慎加载单个文件。(在命令中添加标志,如下所示java -jar MyJar.jar --spring.config.location=D:\test\:)Pivotal 为 Spring Boot 提供了超级好的参考。第 24 节涵盖的属性比我在帖子中更广泛。
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html(*链接到最新版本的参考)
注意:我不是 Windows 用户,因此请小心粘贴上面的文件路径。编辑我。
将配置扩展到可部署包
通常,Spring Boot 会打包成可执行的 WAR 或 JAR,其中包含用于运行时的嵌入式 servlet 容器引擎。然而,在您的情况下,您正在打包传统的 WAR 并将其部署到 Tomcat 的外部实例,因此必须使用 JAVA_OPTS 变量通过 Tomcat 传播配置参数。
对于 Apache Tomcat,惯例是将属性放置在${catalina_base}/confcatalina.base 指向 Tomcat 实例位置的位置。我刚刚按照以下步骤创建了一个工作演示:
mvn packageset JAVA_OPTS=-Dspring.config.location=${catalina.base}/conf/"%CATALINA_HOME%"\bin\startup它不是最干净的部署管道,但如果您必须使用外部 Tomcat 实例,那么这将起作用。但是,在同一个 Tomcat 实例上运行具有单独属性文件的多个应用程序会使事情变得复杂。在这种情况下,使用 Spring Framework(而不是 Boot)会更容易配置。