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

问题描述 投票:0回答:1

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

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

spring-boot properties configuration config configuration-files
1个回答
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));
    }
}

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
@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
© www.soinside.com 2019 - 2024. All rights reserved.