一种解决方案可能是将 application-{profile}.properties 加载为 @PropertySource 注释,正如 question 所建议的那样,但随后日志系统将无法工作,正如您在 documentation 中看到的那样。
日志系统在应用程序生命周期的早期初始化
并且在属性文件中找不到这样的日志记录属性
通过@PropertySource 注解加载。
这意味着您在 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”来加载所有应用程序-{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