![](/img/trans.png)
[英]Why does Spring continue to initialize the context even if a bean fails to instantiate?
[英]Why does in my case context creates the bean?
你能告訴我為什么在我的案例上下文中創建了"simple"
bean,如果它有循環依賴關系? 在我看來,必須拋出一個關於循環依賴的異常! 配置類:
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "service")
public class AppConfig {
}
簡單的課程:
package service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Simple {
@Autowired
private Simple simple;
public Simple getSimple() {
return simple;
}
}
和發射器:
import config.AppConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import service.Simple;
public class Launcher {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
Simple simple1 = ctx.getBean("simple", Simple.class);
System.out.println(simple1.getSimple());
}
}
該應用程序的輸出是“service.Simple@6b53e23f”。 如果我添加構造函數
@Autowired
public Simple(Simple simple) {
this.simple = simple;
}
然后是一個異常"Error creating bean with name 'simple': Requested bean is currently in creation: Is there an unresolvable circular reference?"
發生。
那么為什么在我將@Autowired
放在字段中時會創建bean?
因為simple
字段的設置僅在創建Simple
實例之后完成,並且此時您具有要分配給該字段的有效Simple
實例。 這是現場注入。 創建Simple
類的實例時,不需要自動裝配字段的實例。
另一方面,使用構造函數注入需要所有構造函數參數的有效實例。 所以,你需要一個Simple
實例來創建實例Simple
這當然是行不通的。
因此,當它試圖創建一個bean時,它會首先嘗試解析所有Autowired(依賴注入)。 在我們的例子中,您正在嘗試注入相同的類。 這意味着Spring在創建Simple bean時會嘗試解析注入的類,而這些類又是同一個類。
有一個循環依賴項會拋出錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.