@Autowired的“原型”实例有多少个实例。在@component的使用过程中创建bean是(是)
我有一个Manager
@component
和@scope
的类
@Component
@Scope(value = "prototype")
public class Manager {
...
}
,因此我希望Manager
bean的新实例每次请求Bean时都会创建。
然后,我有一个适配器
类,该类使用此Manager
bean。要使用它,我有两种汽车的方法:1。在属性上或2。在构造函数上:
@Component
public class Adapter {
@Autowired
Manager m_Manager;
...
}
或
@Component
public class Adapter {
Manager m_manager;
@Autowired
public Adapter(Manager manager) {
m_manager = manager;
}
...
}
因为aDapter
class class class class as singleton bean,因此@Autowire
属性或构造函数上的Manager
仅创建Manager
的一个实例?含义Manager
bean实际上用作单身bean而不是原型bean,对吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
@Autowire的行为与ApplicationContext.getBean相同,
它为每个自动实例创建一个原型BEAN。您可以看到两个单例中的原型对象具有不同的标识符
如果您在构造函数或字段中使用@Autowire进行@Autowire,则没有任何区别。
do autowire on构造器只是避免注释重复的更方便的方法。
PS定义范围最好使用
@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
如果您没有任何其他注入点,则在您注入管理器实例的地方,则在应用程序上下文中只有一个实例,这是正确的。
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.