是否可以使用Spring Boot对属性进行分组?

时间:2019-04-26 14:28:01

标签: spring-boot properties configuration config configuration-files

可以使用Spring Boot完成类似的事情吗? enter image description here

这个想法是对属性进行分组,并为所有属性分配相同的值,因此,我想只更改一个属性“ my.flag”,而不是所有以“ test *”结尾的属性。我知道这种功能适用于记录器,但是我可以定义自己的组吗?

1 个答案:

答案 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
    }
}

另请参见
Creating a Custom Starter with Spring Boot

相关问题