@Autowired的“原型”实例有多少个实例。在@component的使用过程中创建bean是(是)

发布于 2025-01-24 00:32:18 字数 880 浏览 1 评论 0原文

我有一个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 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:

@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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

傲影 2025-01-31 00:32:18

@Autowire的行为与ApplicationContext.getBean相同,

它为每个自动实例创建一个原型BEAN。您可以看到两个单例中的原型对象具有不同的标识符

​如果您在构造函数或字段中使用@Autowire进行@Autowire,则没有任何区别。
do autowire on构造器只是避免注释重复的更方便的方法。

PS定义范围最好使用

@Scope(BeanDefinition.SCOPE_PROTOTYPE)

@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)
笔芯 2025-01-31 00:32:18

如果您没有任何其他注入点,则在您注入管理器实例的地方,则在应用程序上下文中只有一个实例,这是正确的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文