简体   繁体   English

使用Autowire检索范围内的原型的bean

[英]Retrieving beans that are Scoped prototype with Autowire

In my XML configuration I have this: 在我的XML配置中,我有以下内容:

<bean id="soap" class="org.grocery.item.Soap" scope="prototype">
        <property name="price" value="20.00" />
</bean>

And in my service class I have the "soap" autowired like this: 在我的服务类中,我将“ soap”自动布线为:

@Autowired
private Soap soap;
//Accessor methods

And I created a test class like this: 我创建了一个这样的测试类:

Item soap = service.getItem(ITEM.SOAP);
Item soap2 = service.getItem(ITEM.SOAP);

if(soap2 == soap ){
    System.out.println("SAME REFERENCE");
}

And this is my getItem method in my service class: 这是我的服务类中的getItem方法:

public Item item(Item enumSelector) {
        switch (enumSelector) {
            case SOAP:
                return this.getSoap();
        }
        return null;
    }

@Autowired
private Soap soap;
//Accessor methods

Now what I am expecting is that the when I call the this.getSoap(); 现在我期望的是,当我调用this.getSoap();时。 it will return a new Soap object. 它将返回一个新的Soap对象。 However, it did not, even though the soap is declared scoped as prototype. 但是,即使肥皂被声明为原型,它也没有。 Why is that? 这是为什么?

创建服务对象时,spring会将肥皂对象实例注入到服务对象中,因此对服务的getSoap()的所有调用都将检索创建服务时注入的相同肥皂对象。

Renjith explained the why in his answer. 伦吉斯在回答中解释了原因。 As for the how, I know of 2 ways to achieve this: 至于如何,我知道两种方法可以做到这一点:

  1. lookup method: 查找方法:

Don't declare the soap dependency as a field, but rather as an abstract getter method: 不要将soap依赖项声明为字段,而应声明为抽象的getter方法:

protected abstract Soap getSoap();

Whenever you need the soap in your service (like in the getItem method), call the getter. 每当您在服务中需要肥皂时(例如在getItem方法中)​​,请调用getter。

In the xml config, instruct Spring to implement that method for you: 在xml配置中,指示Spring为您实现该方法:

<bean id="service" class="foo.YourService">
  <lookup-method name="getSoap" bean="soapBeanId"/>
</bean>

The Spring supplied implementation would fetch a fresh instance of Soap whenever called. 每次调用时,Spring提供的实现都会获取一个Soap的新实例。

  1. Scoped proxies 代理范围

This instructs Spring to inject a proxy instead of the real Soap instance. 这指示Spring注入代理而不是真实的Soap实例。 The injected proxy methods would lookup the correct soap instance (a fresh one since it's a prototype bean) and delegate to them: 注入的代理方法将查找正确的soap实例(因为它是原型Bean,所以是一个新鲜的实例)并委托给它们:

<bean id="soap" class="foo.Soap">
  <aop:scoped-proxy/>
</bean>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM