Looping link exclusion
I have a question about spring framework. Let's assume the following code exists:
@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 the following code appears, which launches the application context:
@SpringBootApplication
public class DemoApplication
{
@Autowired
private A a;
public static void main(String[] args)
{
SpringApplication.run(DemoApplication.class, args);
}
}
if i start the spring context then it will throw a circular reference exception (which is expected). My question is, why if I rescale bean A to singleton then everything works fine?
+3
source to share
1 answer
omitted - like injection, since it occurs 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 create bean A ........
for singelton you are using the only object that was created before you reference it
0
source to share