【问题标题】:How do I add a JPA based PropertySource to external configuration in Spring boot如何在 Spring Boot 中将基于 JPA 的 PropertySource 添加到外部配置
【发布时间】:2014-10-30 14:54:43
【问题描述】:

我一直在尝试将自定义 PropertySource 添加到 spring Environment bean,但无法使其正常工作。我有一个 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,但没有任何数据,因为ConfigurationDao@Autowired 为空。我已经在其他地方连接了ConfigurationDao,它确实有效,并且可以通过它访问数据。我只是认为这是启动期间的时间问题,但我不确定如何订购/计时。有没有人做过类似的事情并且可以提供任何帮助来实现这一点。

【问题讨论】:

    标签: java spring spring-boot configuration spring-data-jpa


    【解决方案1】:

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

    【讨论】:

    • 叹息,所有这些都只适用于从数据库进行配置。这让我这个懒惰的开发者畏缩了:(
    • 懒惰是好的。这是一个样板模式,所以也许它应该在 Spring Boot 中(在 github 中很容易提出问题,并且几乎同样容易发送拉取请求)。
    猜你喜欢
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 2017-11-26
    • 2014-02-10
    • 1970-01-01
    相关资源
    最近更新 更多