从数据库加载Spring Boot配置

时间:2019-04-02 18:44:25

标签: java spring-boot

我正在创建一个ApplicationListener,其中要从数据库中加载自定义键/值配置属性,并创建一个MapPropertySource对象。但是,当我想在目标@Configuration对象中使用带前缀(或不带前缀)的对象时,它们为null。无法在PropertySource中引用MapPropertySource

我也尝试实现ApplicationContextInitializer,但是没有用。

public class PropertiesContextInitializer implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private ConfigurableEnvironment configurableEnvironment;
    @Autowired
    private DatabasePropertyRepository propertiesRepository;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        Map<String, Object> propertySource = new HashMap<>();
        List<DatabaseProperty> result = propertiesRepository.findAll();

        result.forEach((x) -> {
            propertySource.put(x.getService().toLowerCase() + "." + x.getName(), x.getValue());
        });

        propertySource.forEach((k, v) -> System.out.println((k + "=" + v)));


        configurableEnvironment.getPropertySources()
                .addLast(new MapPropertySource("dbConfigProperties", propertySource));
    }
}

然后我尝试在Spring Boot主类中添加以下内容: SpringApplication.run(IntegrationApplication.class, args).addApplicationListener(new PropertiesContextInitializer());

我的目标类定义应使用此自定义属性(我使用前缀,但也尝试不使用前缀):

@ConfigurationProperties("myconf")
public class MyConfig ...

0 个答案:

没有答案