2017-07-03 70 views
0

我有一個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。我只是說依賴於搖籃配置:

compile("org.springframework.boot:spring-boot-starter-data-jpa") 

後,我加入的依賴,我可以看到一個例外,而應用程序正在啓動:

錯誤名爲「persistentConfiguration」創建豆: 注射液自動裝配依賴性失敗;嵌套的例外是 java.lang.IllegalArgumentException異常:無法解析的佔位符 'db.url配置參數' 中值「$ {} db.url配置參數

如果我刪除依賴的應用程序沒有問題開始

。並獲取數據,即使沒有被調用了哪些配置客戶端,並調用它以前的類

回答

1

爲了讓Spring知道它應該處理您的ContextConfiguration首先,添加一個DependsOn annotationPersistentConfiguration像這樣:

@DependsOn("contextConfiguration") 
@Configuration 
public class PersistentConfiguration { 
    ... 

問題是你的PersistentConfiguration沒有告訴Spring它取決於ContextConfiguration,儘管它的確如此,因爲前者只使用後者初始化的變量。

這正是DependsOn的用途。來自JavaDoc:

指定的任何bean都保證由容器在此bean之前創建。在bean沒有明確依賴另一個屬性或構造函數參數的情況下使用,而是依賴於另一個bean的初始化的副作用。

+0

謝謝!它有幫助 – migAlex