Typically in Spring Context if a prototype bean is injected in a singleton bean, property of parent class overrides prototype bean scope. However what will happen if a singleton scope bean is injected in prototype bean scope. Still using get bean of the inner bean will return with new instance of inner bean?
1
votes
2 Answers
3
votes
No, all instances of prototype
bean will share the same instance of the singleton
bean.
Example:
@Service
public class SingletonBean {
private int id;
private static int static_id = 0;
public SingletonBean() {
id = static_id++;
}
@Override
public String toString() {
return "SingletonBean [id=" + id + "]";
}
}
@Service
@Scope("prototype")
public class PrototypeBean {
@Autowired
private SingletonBean singletonBean;
private int id;
private static int static_id = 0;
public PrototypeBean() {
id = static_id++;
}
@Override
public String toString() {
return "id=" + id + ", PrototypeBean [singletonBean=" + singletonBean + "]";
}
}
@SpringBootApplication public class DemoApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args); PrototypeBean beanA = context.getBean(PrototypeBean.class); PrototypeBean beanB = context.getBean(PrototypeBean.class); System.out.println(beanA); //id=0, PrototypeBean [singletonBean=SingletonBean [id=0]] System.out.println(beanB); //id=1, PrototypeBean [singletonBean=SingletonBean [id=0]] } } </code>
0
votes
Typically in Spring Context if a prototype bean is injected in a singleton bean, property of parent class overrides prototype bean scope.
That is true,but not always, you can override that using Lookup method injection, which make you able to inject new prototype object in every request , check documentation for a complete example about it,
for your main question the singleton is created once when the context is loaded and then whoever called this singleton the context give the same instance , without taking on consideration who making the call