我在将 Spring Boot YAML 属性注入 log4j xml 配置时遇到了类似的问题,我找到了 Spring Boot 1.5.X(可能是 2.0,我没有测试它)的解决方案,这有点 hacky 和对系统属性查找进行操作,但它确实有效。
假设您的应用程序中有配置文件“dev”和一些要注入的属性,那么您的 application-dev.yml 看起来像这样:
property:
toInject: someValue
在你的 xml 配置 log4j2-spring-dev.xml 你把这样的东西:
<Properties>
<property name="someProp">${sys:property.toInject}</property>
</Properties>
现在您必须以某种方式将此弹簧属性转移到系统属性。您必须在准备好应用程序环境之后和日志系统初始化之前执行此操作。在 Spring Boot 中有一个监听器 LoggingApplicationListener,它初始化整个日志系统,它是由事件 ApplicationEnvironmentPreparedEvent 触发的,所以让我们创建一个比 LoggingApplicationListener 优先级更高的监听器:
public class LoggingListener implements ApplicationListener, Ordered {
@Override
public int getOrder() {
return LoggingApplicationListener.DEFAULT_ORDER - 1;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
ConfigurableEnvironment environment = ((ApplicationEnvironmentPreparedEvent) event).getEnvironment();
List<String> activeProfiles = Arrays.asList(environment.getActiveProfiles());
if (!activeProfiles.contains("dev")) {
return;
}
String someProp = environment.getProperty("property.toInject")
validateProperty(someProp);
System.setProperty("property.toInject", someProp);
}
}
现在在你的应用中注册这个监听器:
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);
application.addListeners(new LoggingListener());
application.run(args);
}
就是这样。您的 Spring Boot 属性应该在您的 log4j2 配置文件中“注入”。此解决方案适用于类路径属性和 --spring.config.location 属性。请注意,它不适用于 Spring Cloud Config 等外部配置系统。
希望对你有帮助