java为什么在我的例子中创建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());
}
}
应用程序的输出是“服务”。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呢
# 1 楼答案
因此,spring在尝试创建bean时,首先尝试解决所有自动连接(依赖项注入)问题。在我们的例子中,您试图注入相同的类。这意味着,Spring在创建简单bean时,会尝试解析注入的类,而注入的类又是同一个类
有一个循环依赖项抛出错误
# 2 楼答案
因为
simple
字段的设置只有在创建Simple
实例之后才能完成,此时您有一个有效的Simple
实例要分配给该字段。这就是现场注射。在创建Simple
类的实例时,不需要自动连接字段的实例另一方面,使用构造函数注入,您需要所有构造函数参数的有效实例。因此,您需要一个
Simple
实例来创建Simple
的实例,这当然不起作用