我需要创建一个属性源来从数据库表中读取属性。在寻找如何实现这一点时,我找到了两种方法,需要创建文件spring.factories
并注册特定的类。
例如,我可以使用Events
和ApplicationEnvironmentPreparedEvent
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,但我还不清楚使用每种方法的优点和缺点是什么,何时我应该选择其中一种,或者实际上是否有更好的方法做这个。有人可以给我一些澄清吗?