Sobes.tech
Junior

Spring: how many instances of a bean with @Component are created if it is injected in two places? How to create a new instance for each injection?.

sobes.tech AI

Answer from AI

If a bean is annotated with @Component and injected in two places, by default Spring will create a single singleton instance of this bean and use it everywhere.

To create a new instance of the bean each time it is injected, you need to change the bean's scope to prototype:

@Component
@Scope("prototype")
public class MyBean {
    // ...
}

In this case, Spring will create a new bean instance each time it is injected.

Important: When using prototype beans within singleton beans, you should be aware that Spring will not automatically create new instances upon each call, only when the singleton bean itself is created. To dynamically obtain new instances, you can use ObjectFactory or Provider.

Spring: how many instances of a bean with @Component… - sobes.tech