2
我有一個包含多個組件和配置類的Spring Boot項目。在我的項目中,我注意到自動佈線字段的順序導致了不同的場景。有時我會得到Nullpointer-Exceptions,而Spring Boot正在抱怨循環引用,但是按照正確的順序排列,一切正常。Spring Boot:Autowired註釋的順序有時會導致循環引用
我能夠重現我的問題與這個簡單的代碼片段:
的Component1:
@Component
public class Properties {
public String getHost() {
return "some.address.com";
}
public int getPort() {
return 8080;
}
}
COMPONENT2:
@Component
public class WebClient {
@Autowired
String webadress;
public void callWebAdress() {
System.out.println("Getting Data from " + webadress);
}
}
應用:
@SpringBootApplication
public class Application {
@Autowired
WebClient webClient;
@Autowired
Properties props;
@Bean
String webAdresss(){
return "http://+"+props.getHost()+":"+props.getPort();
}
@PostConstruct
void init(){
webClient.callWebAdress();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
這CONFI現在導致一個循環引用問題。但是,當我在我的應用程序類中更改字段webClient
和props
的順序時,一切正常。我知道還有其他幾個選項可以讓代碼運行,例如自動裝配屬性作爲方法參數,自動裝配WebClient中的屬性Bean。但是這些選項對我的簡單例子來說工作得很好,但是它們會降低我更復雜代碼的易讀性。
我不明白,在這個問題這個問題:
- 爲什麼春天不能夠找出創建豆的正確順序?
- 一般我怎樣才能構造多個
Configuration
類和Components
? - 如何構造配置以避免有關自動裝配順序的問題?
引用/豆的依賴關係相互:
(橙色裝置自動連接,黃色表示豆和白色是指成分)
您是否嘗試過'@ ConfigurationProperties'。文檔 - http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties –
你有沒有嘗試過@Bean String webAdress(屬性道具){return「http:// +」+ props.getHost()+「:」+ props.getPort();}' –
imho最大的缺陷是你試圖做一個簡單的屬性('webAddress ')一個你最初不應該做的事。 –