如何在Spring Boot中将基于JPA的PropertySource添加到外部配置 [英] How do I add a JPA based PropertySource to external configuration in Spring boot
问题描述
我一直在尝试向春季 Environment
bean添加自定义的 PropertySource
,但是无法使其正常工作。我有一个Spring Boot应用程序,并且已经成功完成了以下操作
I've been trying to add a custom PropertySource
to the spring Environment
bean but cannot get it to work. I have a Spring boot application and have managed to do the following
@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);
}
这肯定会添加 DatabasePropertySource
到 StandardServletEnvironment
,但是没有任何数据作为 ConfigurationDao
@自动连线为空。我已经将 ConfigurationDao
连接到其他地方,它确实可以工作并且可以通过它访问数据。我只是认为这是启动过程中的时间问题,但是我不确定如何订购/计时。有没有人做过类似的事情,并提供任何帮助来实现这一目标。
This definitely adds a DatabasePropertySource
to the StandardServletEnvironment
but there isn't any data as the ConfigurationDao
that is @Autowired
is null. I have wired in the ConfigurationDao
elsewhere and it does work and data is accessible through it. 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.
推荐答案
让JPA及时启动以包括在环境
中可能是不可能的(它是鸡肉和鸡蛋)。打破周期的一种方法是在父上下文中初始化数据库和存储库,然后在子级的环境
中使用它(您的主应用程序上下文)。在 SpringApplicationBuilder
中有方便的方法来构建父级和子级上下文。
Getting JPA to start up in time to include it in the Environment
is probably impossible (it's chicken and egg). 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). There are convenience methods for building parent and child contexts in SpringApplicationBuilder
.
这篇关于如何在Spring Boot中将基于JPA的PropertySource添加到外部配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!