循环引用异常

时间:2017-06-26 18:31:56

标签: java spring

我对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的范围更改为单例,那么一切都会正常工作吗?

1 个答案:

答案 0 :(得分:0)

被省略 - 就像在创建对象之后的注入一样。

原型看起来像(没有弹簧)

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 A ........

从bean B创建bean A.

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