想法是对属性进行分组,并为所有属性分配相同的值,因此,我不想更改所有以'test *'结尾的属性,而是仅更改一个属性'my.flag'。我知道这种功能适用于记录器,但是我可以定义自己的组吗?
我不确定您的问题是否已解决,但是我想提供一种解决方案,通过使用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)); } }
STEP 2
spring.factories
下创建一个名为src/main/resource/META-INF
的文件并将其配置为MyPropertiesListener
。org.springframework.context.ApplicationListener=xxx.xxx.xxx.MyPropertiesListener
TEST
my.flag.test3
的值最初是false
中的application.properties
,但是在应用程序启动时它将被覆盖为true
。Creating a Custom Starter with Spring Boot@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 } }
另见