ApplicationEnvironmentPreparedEvent和EnvironmentPostProcessor之间的区别是什么?

时间:2017-03-27 21:06:18

标签: java spring spring-boot

我需要创建一个属性源来从数据库表中读取属性。在寻找如何实现这一点时,我找到了两种方法,需要创建文件spring.factories并注册特定的类。

例如,我可以使用EventsApplicationEnvironmentPreparedEvent

public class DatabasePropertiesListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        Properties props = new Properties();
        props.put("spring.datasource.url", "<my value>"); // READ FROM DB AND CONFIGURE ALL PROPS HERE
        environment.getPropertySources().addFirst(new PropertiesPropertySource("dbProps", props));
    }
}

spring.factories档案:

org.springframework.context.ApplicationListener=com.DatabasePropertiesListener

或者使用带有EnvironmentPostProcessor的环境后处理器:

public class DatabasePropertiesEnvPostProcessor implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Properties props = new Properties();
        props.put("spring.datasource.url", "<my value>"); // READ FROM DB AND CONFIGURE ALL PROPS HERE
        environment.getPropertySources().addFirst(new PropertiesPropertySource("dbProps", props));
    }
}

spring.factories档案:

 org.springframework.boot.env.EnvironmentPostProcessor=com.DatabasePropertiesListener

我读了documentation,但我还不清楚使用每种方法的优点和缺点是什么,何时我应该选择其中一种,或者实际上是否有更好的方法做这个。有人可以给我一些澄清吗?

0 个答案:

没有答案