2017-05-08 73 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

相关问题