3

I have question about spring framework. So assume there is following code:

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

and there is following code which starts application context:

@SpringBootApplication
public class DemoApplication
{
  @Autowired
  private A a;

  public static void main(String[] args)
  {
    SpringApplication.run(DemoApplication.class, args);
  }
}

if I start spring context then it will throw circular reference exception(which is expected). My question is why if I change the scope of bean A to singleton then everything will work fine?

Alex
  • 1,940
  • 2
  • 18
  • 36
  • 1
    With prototype scope, you'll create an A, which will create a B, which will create an A, which will create a B... forever. With singleton scope, you'll create an A, which will create a B, which will autowire back to A. – Compass Jun 26 '17 at 18:34
  • Possible duplicate of [What is difference between singleton and prototype bean?](https://stackoverflow.com/questions/16058365/what-is-difference-between-singleton-and-prototype-bean) – Compass Jun 26 '17 at 18:36

1 Answers1

0

are omitted - like injection as it's come after objects are created.

with prototype it looks like (without spring)

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

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

with singeltone it looks like (without 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;
  }
}

for prototype you create bean A from bean B with creation bean A ........

for singelton you use single object that was created before you use reference on it

xyz
  • 5,228
  • 2
  • 26
  • 35
  • do you know if situation will change if I change scope from prototype to request? – Alex Jun 26 '17 at 19:28
  • yes / no. inside one request it be singelton , if you have two or more different request it's be as prototype for different request. same for session scope – xyz Jun 26 '17 at 19:31