[英]How do I add a JPA based PropertySource to external configuration in Spring boot
I've been trying to add a custom PropertySource
to the spring Environment
bean but cannot get it to work. 我一直在尝试向Spring Environment
bean添加自定义PropertySource
,但无法使其正常工作。 I have a Spring boot application and have managed to do the following 我有一个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);
}
This definitely adds a DatabasePropertySource
to the StandardServletEnvironment
but there isn't any data as the ConfigurationDao
that is @Autowired
is null. 这肯定会在StandardServletEnvironment
添加DatabasePropertySource
,但是没有任何数据,因为@Autowired
的ConfigurationDao
为null。 I have wired in the ConfigurationDao
elsewhere and it does work and data is accessible through it. 我已经将ConfigurationDao
连接到其他地方,并且它确实可以工作并且可以通过它访问数据。 I just think it is a matter of timing during startup but I'm not sure exactly how to order/time it. 我只是认为这是启动过程中的时间问题,但是我不确定如何订购/计时它。 Has anyone done something similar and have any help to offer to make this happen. 有没有人做过类似的事情,并提供任何帮助来实现这一目标。
Getting JPA to start up in time to include it in the Environment
is probably impossible (it's chicken and egg). 及时启动JPA以将其包含到Environment
中可能是不可能的(这是鸡和蛋)。 One way to break the cycle is to initialize your database and repository in a parent context, and then use it in the Environment
of the child (your main application context). 打破周期的一种方法是在父上下文中初始化数据库和存储库,然后在子Environment
(您的主应用程序上下文)中使用它。 There are convenience methods for building parent and child contexts in SpringApplicationBuilder
. 在SpringApplicationBuilder
有一些方便的方法来构建父上下文和子上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.