我有一个 Spring Boot 应用程序。我有一个配置服务应用程序,它为我的应用程序提供所有配置。我创建了一个客户端,它提取应用程序的所有设置并将它们放入上下文中。 我创建了执行此工作的 java 类:
@Configuration
public class ContextConfiguration {
@PostConstruct
public void getContextConfiguration(){
ConfigServiceResponse configurations = configurationServiceClient.getConfigurations(configurationEnv);
Properties properties = generateProperties(configurations.getConfigParameterList());
MutablePropertySources propertySources = env.getPropertySources();
propertySources.addFirst(new PropertiesPropertySource("APPLICATION_PROPERTIES", properties));
}
}
我还创建了用于配置数据源的java类:
@Configuration
public class PersistentConfiguration {
@Value("${db.url}")
private String serverDbURL;
@Value("${db.user}")
private String serverDbUser;
@Value("${db.password}")
private String serverDbPassword;
public DataSource dataSource() {
return new SingleConnectionDataSource(serverDbURL, serverDbUser, serverDbPassword, true);
}
}
通过此配置,应用程序运行良好。直到我迁移到 Spring Data。我刚刚添加了对 Gradle 配置的依赖:
compile("org.springframework.boot:spring-boot-starter-data-jpa")
添加依赖项后,我可以在应用程序启动时看到异常:
Error creating bean with name 'persistentConfiguration': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'db.url' in value "${db.url}
如果我删除依赖项,应用程序启动时不会出现任何问题。
并且之前配置客户端并调用它来获取数据的类甚至没有被调用。
最佳答案
为了让 Spring 知道它应该首先处理您的 ContextConfiguration
,请添加 DependsOn
annotation像这样的PersistentConfiguration
:
@DependsOn("contextConfiguration")
@Configuration
public class PersistentConfiguration {
...
问题是,PersistentConfiguration
中没有任何内容告诉 Spring 它依赖于 ContextConfiguration
,尽管它确实依赖于 ContextConfiguration
,因为前者使用仅由后者初始化的变量。
这正是 DependsOn
的用途。来自 JavaDoc:
Any beans specified are guaranteed to be created by the container before this bean. Used infrequently in cases where a bean does not explicitly depend on another through properties or constructor arguments, but rather depends on the side effects of another bean's initialization.
关于java - Spring数据初始化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44892773/