这个想法是对属性进行分组,并为所有属性分配相同的值,因此,我想只更改一个属性“ my.flag”,而不是所有以“ test *”结尾的属性。我知道这种功能适用于记录器,但是我可以定义自己的组吗?
答案 0 :(得分:0)
我不确定您的问题是否已解决,但是我想提供一种解决方案,通过使用spring.factories
并按照以下步骤实施ApplicationListener
来实现所需的目标。
STEP 1
创建一个实现MyPropertiesListener
的类ApplicationListener
,并首先在my.flag
中读取application.properties
的值,然后将其设置为键以my.flag.
开头的所有属性。
public class MyPropertiesListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment env = event.getEnvironment();
String myFlag = env.getProperty("my.flag");
Properties props = new Properties();
MutablePropertySources propSrcs = env.getPropertySources();
StreamSupport.stream(propSrcs.spliterator(), false)
.filter(ps -> ps instanceof EnumerablePropertySource)
.map(ps -> ((MapPropertySource) ps).getPropertyNames())
.flatMap(Arrays::<String>stream)
.forEach(propName -> {
if (propName.toString().startsWith("my.flag.")) {
props.put(propName, myFlag);
}
});
env.getPropertySources().addFirst(new PropertiesPropertySource("myProps", props));
}
}
第2步
在spring.factories
下创建一个名为src/main/resource/META-INF
的文件,并将MyPropertiesListener
配置到其中。
org.springframework.context.ApplicationListener=xxx.xxx.xxx.MyPropertiesListener
测试
my.flag.test3
的值最初是false
中的application.properties
,但是在应用程序启动时它将被覆盖为true
。
@SpringBootApplication
public class Application implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Value("${my.flag.test3}")
private String test3;
@Override
public void run(String... args) throws Exception {
System.out.println(test3); //true
}
}