循环参考例外



我对春季框架有疑问。因此,假设有以下代码:

@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);
  }
}

如果我开始春季上下文,则会引发循环参考异常(预期(。我的问题是,为什么我将Bean A的范围更改为Singleton,那么一切都会正常工作?

被省略 - 在创建对象之后出现时喜欢注入。

带有原型,它看起来像(无春季(

public class A{
  private B b =new B();
}
public class B{
  private A a =new A();
}

与Singeltone一起看起来像(无春季(

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;
  }
}

对于原型,您可以从bean b中与Creation Bean A创建Bean A ........

对于Singelton,您使用在使用引用之前创建的单个对象

最新更新