繁体   English   中英

如何在Spring Boot中将基于JPA的PropertySource添加到外部配置

[英]How do I add a JPA based PropertySource to external configuration in Spring boot

我一直在尝试向Spring Environment bean添加自定义PropertySource ,但无法使其正常工作。 我有一个Spring Boot应用程序,并设法完成了以下操作

@Bean
public Environment environment() {
    ConfigurableEnvironment environment = new StandardServletEnvironment();
    MutablePropertySources propertySources = environment.getPropertySources();  
    propertySources.addFirst(new DatabasePropertySource("databaseProperties"));
    return environment;
}

public class DatabasePropertySource extends PropertySource<DatabaseReaderDelegate> {

    public DatabasePropertySource(String name) {
        super(name, new DatabaseReaderDelegate());
    }

    @Override
    public Object getProperty(String name) {
        return this.source.getProperty(name);
    }
}

public class DatabaseReaderDelegate {

    @Autowired ConfigurationDao dao;

    public Object getProperty(String property) {
        Configuration object = dao.findOneByConfKey(property);
        Object value = object.getConfValue();
        return value;
    }
}

public interface ConfigurationDao extends JpaRepository<Configuration, Long> {
    Configuration findOneByConfKey(String name);
}

这肯定会在StandardServletEnvironment添加DatabasePropertySource ,但是没有任何数据,因为@AutowiredConfigurationDao为null。 我已经将ConfigurationDao连接到其他地方,并且它确实可以工作并且可以通过它访问数据。 我只是认为这是启动过程中的时间问题,但是我不确定如何订购/计时它。 有没有人做过类似的事情,并提供任何帮助来实现这一目标。

及时启动JPA以将其包含到Environment中可能是不可能的(这是鸡和蛋)。 打破周期的一种方法是在父上下文中初始化数据库和存储库,然后在子Environment (您的主应用程序上下文)中使用它。 SpringApplicationBuilder有一些方便的方法来构建父上下文和子上下文。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM