Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How many instance(s) of @Autowired "prototype" bean is(are) created during the usage of a @Component

I have a Managerclass annotated with @Component
 and @Scope

@Component
    
@Scope(value = "prototype")
    
public class Manager {
   ...
}

So I expect a new instance of the Manager bean will be created each time the bean is requested.

Then I have an Adapter class which uses this Manager bean. To use it, I have two ways of Autowire: 1. on the property or 2. on the constructor:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@Component
    
public class Adapter {
    @Autowired
    
    Manager m_Manager;

    ...
}

Or

@Component
    
public class Adapter {
    Manager m_manager;

    @Autowired
    
    public Adapter(Manager manager) {
        m_manager = manager;
    }

    ...
}

Since the Adaptor class is a singleton bean, so both @Autowire the Manageron the property or on the constructor will only create one instance of the Manager? Meaning Managerbean is actually used as a singleton bean instead of prototype bean, right?

>Solution :

@Autowire behaves in the same way as ApplicationContext.getBean

It creates a prototype bean for each autowired instance. you can see that the prototype object in two singletons has a different identifierenter image description here

So each singleton has its own prototype instance. It doesn’t have any difference if you do it with @Autowire in the constructor or field.
Do Autowire on constructor is just more convenient way to avoid annotation duplication.

P.S. To define scope is better to use

@Scope(BeanDefinition.SCOPE_PROTOTYPE)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading