我有一个Spring应用程序。我有一个配置服务应用程序,它为我的应用程序提供所有配置。我创建了一个客户机,它提取应用程序的所有设置,并将它们放到上下文中。我创建了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));
}
}此外,我还为DataSource的配置创建了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数据。我刚刚在Gradle配置中添加了依赖项:
compile("org.springframework.boot:spring-boot-starter-data-jpa")添加依赖项之后,当应用程序启动时,我可以看到一个异常:
创建名为“持久化配置”的bean错误:自动配置依赖项的注入失败;嵌套异常为java.lang.IllegalArgumentException:未能解析占位符“db.url”的值"${db.url}“
如果我删除依赖,应用程序开始时没有任何问题。
以前的类配置客户端并调用它获取数据,甚至没有被调用。
发布于 2017-07-04 04:42:47
为了让Spring知道它应该首先处理您的ContextConfiguration,在PersistentConfiguration中添加一个 annotation,如下所示:
@DependsOn("contextConfiguration")
@Configuration
public class PersistentConfiguration {
...问题是,您的PersistentConfiguration中没有任何东西告诉Spring它依赖于ContextConfiguration,尽管它是依赖的,因为前者只使用由后者初始化的变量。
这正是DependsOn的作用所在。来自JavaDoc:
任何指定的bean都保证由容器在此bean之前创建。在bean不通过属性或构造函数参数显式依赖另一个bean,而是依赖于另一个bean初始化的副作用的情况下,很少使用。
https://stackoverflow.com/questions/44892773
复制相似问题