我对 spring 框架有疑问。因此假设有以下代码:
@Service
@Scope("prototype")
public class A
{
@Autowired
private B b;
public void foo()
{
System.out.println("A foo");
}
}
@Service
@Scope("prototype")
public class B
{
@Autowired
private A a;
public void foo()
{
System.out.println("B foo");
}
}
并且有以下代码启动应用程序上下文:
@SpringBootApplication
public class DemoApplication
{
@Autowired
private A a;
public static void main(String[] args)
{
SpringApplication.run(DemoApplication.class, args);
}
}
如果我启动 spring 上下文,那么它将抛出循环引用异常(这是预期的)。我的问题是为什么如果我将 bean A 的范围更改为单例那么一切都会正常工作?
最佳答案
被省略 - 就像注入(inject)一样,因为它是在创建对象之后发生的。
带有原型(prototype),看起来像(没有 Spring )
public class A{
private B b =new B();
}
public class B{
private A a =new A();
}
使用单音看起来像(没有 Spring )
public class A{
private static A a = new A();
private static B b = B.getB();
public static B getB(){
return b;
}}
public class B{
private static B b = new B();
private static A a = A.getA();
public static B getB(){
return b;
}
}
对于原型(prototype),您使用创建 bean A 从 bean B 创建 bean A ........
对于单例,您使用在使用引用之前创建的单个对象
关于java - 循环引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44766363/