I have a Manager
class 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:
@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 Manager
on the property or on the constructor will only create one instance of the Manager
? Meaning Manager
bean is actually used as a singleton bean instead of prototype bean, right?
CodePudding user response:
@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 identifier
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)
CodePudding user response:
If you don't have any other injection points, where you inject a Manager instance, then you will only have one instance in the application context, that's correct.