2017-05-08 23 views
0

我有以下Spring bean與原型範圍。在AppRunner類中,我希望在for循環中通過spring注入一個新bean(如果循環計數爲2,那麼我只需要注入兩個新的bean)。Spring bean如何與Prototype範圍一起工作?

但是每次調用SimpleBean的setter方法時,spring都會注入一個新的bean。

SimpleBean.java

@Component 
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode = 
ScopedProxyMode.TARGET_CLASS) 
public class SimpleBean { 
    private String id; 
    private Long value; 
    public String getId() { 
     return id; 
    } 

    public void setId(String id) { 
     this.id = id; 
    } 

    public Long getValue() { 
     return value; 
    } 

    public void setValue(Long value) { 
     this.value = value; 
    } 
} 

AppRunner.java

@Component 
public class AppRunner { 

    @Autowired 
    SimpleBean simpleBean; 

    public void execute(List<Output> results){ 
     List<SimpleBean> finalResults = new ArrayList<SimpleBean>(); 
     for(Output o : results){ 
      simpleBean.setId(o.getAppId()); 
      simpleBean.setValue(o.getAppVal()); 
      finalResults.add(simpleBean); 
     } 
    } 
} 

Output.java

public class Output { 
    private String appId; 
    private Long appVal; 

    public String getAppId() { 
     return appId; 
    } 

    public void setAppId(String appId) { 
     this.appId = appId; 
    } 

    public Long getAppVal() { 
     return appVal; 
    } 

    public void setAppVal(Long appVal) { 
     this.appVal = appVal; 
    } 
} 

回答

0

不幸的是原型範圍並不像這樣工作。當你的bean被容器實例化時,它要求它的依賴關係。然後創建一個SimpleBean的新實例。這個實例保持依賴關係。當您將有多個依賴於SimpleBean的豆時,原型範圍開始工作。像:

@Component 
class BeanOne { 
    @Autowired 
    SimpleBean bean; //will have its own instance 
} 

@Component 
class BeanTwo { 
    @Autowired 
    SimpleBean bean; //another instance 
} 

有一個相當直接的更新,可以導致你想要的行爲。您可以刪除自動裝配的依賴關係,並從上下文中請求循環中的新依賴項。它看起來像這樣。

@Component 
public class AppRunner { 

    @Autowired 
    ApplicationContext context; 

    public void execute(List<Output> results){ 
     List<SimpleBean> finalResults = new ArrayList<SimpleBean>(); 
     for(Output o : results) { 
      SimpleBean simpleBean = context.getBean(SimpleBean.class); 
      simpleBean.setId(o.getAppId()); 
      simpleBean.setValue(o.getAppVal()); 
      finalResults.add(simpleBean); 
     } 
    } 
} 

其他選項可以被稱爲技術Method injection。在原型範圍的相關文檔中有描述。你可以看看這裏7.5.3 Singleton beans with prototype-bean dependencies

+0

感謝您的詳細信息。 – Vel