如何将Spring Boot application.properties外部化到tomcat / lib文件夹
作者:互联网
我需要一个免配置,可部署的war,myapp1.war,它可以从tomcat / lib文件夹中检索配置文件.
由于我有其他Web应用程序共存于同一个Tomcat:myapp2.war,myapp3.war,我需要这个布局:
tomcat/lib/myapp1/application.properties
tomcat/lib/myapp2/application.properties
tomcat/lib/myapp3/application.properties
通过这种方式,我可以在战争中构建war文件而不需要任何属性文件,并在任何服务器上部署.
我已经阅读了Spring documentation,但它解释了如何在作为jar运行时设置位置:
java -jar myapp.jar --spring.config.location=classpath:/default.properties,classpath:/override.properties
对于多个共存战争文件的情况,我无法弄清楚如何做到这一点.
我想知道这是否可行,还是应该放弃Spring Boot并回到传统的Spring MVC应用程序.
解决方法:
解决方案可能是将application- {profile} .properties加载为@PropertySource注释,如question所示,但随后日志系统将无法工作,如您在documentation中所见.
The logging system is initialized early in the application lifecycle
and as such logging properties will not be found in property files
loaded via @PropertySource annotations.
这意味着您在application- {profiles} .properties中的日志记录属性如:
logging.config=classpath:myapp1/logback.xml
logging.path = /path/to/logs
logging.file = myapp1.log
将被忽略,日志系统不会工作.
为了解决这个问题,我在配置应用程序时使用SpringApplicationBuilder.properties()方法在开头加载属性.在那里,我设置了Spring Boot使用的’spring.config.location’来加载所有application- {profiles} .properties:
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder springApplicationBuilder) {
return springApplicationBuilder
.sources(Application.class)
.properties(getProperties());
}
public static void main(String[] args) {
SpringApplicationBuilder springApplicationBuilder = new SpringApplicationBuilder(Application.class)
.sources(Application.class)
.properties(getProperties())
.run(args);
}
static Properties getProperties() {
Properties props = new Properties();
props.put("spring.config.location", "classpath:myapp1/");
return props;
}
}
然后我将属性文件从src / main / resources移动到src / main / resources / myapp1
.
├src
| └main
| └resources
| └myapp1
| └application.properties
| └application-development.properties
| └logback.xml
└─pom.xml
在pom.xml中,我必须将嵌入式tomcat库的范围设置为“提供”.
此外,要从最终的战争中排除src / main / resources / myapp1中的所有属性文件,并生成一个配置免费,可部署的战争:
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<packagingExcludes>
**/myapp1/
</packagingExcludes>
</configuration>
</plugin>
然后在Tomcat我有
├apache-tomcat-7.0.59
└lib
├─myapp1
| └application.properties
| └logback.xml
└─myapp2
└application.properties
└logback.xml
现在我可以生成配置免费战争并将其放入apache-tomcat-7.0.59 / webapps文件夹中.将使用类路径解析属性文件,每个webapp都是独立的:
apache-tomcat-7.0.59/lib/myapp1
apache-tomcat-7.0.59/lib/myapp2
apache-tomcat-7.0.59/lib/myapp3
标签:java,spring-boot,tomcat,maven-3 来源: https://codeday.me/bug/20190923/1815109.html