【问题标题】:Java Spring - Lookup method injection for a ListJava Spring - 列表的查找方法注入
【发布时间】:2015-05-07 13:18:15
【问题描述】:

我有一个当前在我的类中自动装配的对象列表,我想使用新的 spring 查找方法注入,这样每次调用这个列表时,都会返回一个新的 PROTOTYPE bean 列表(我想要一个新对象每个时间,因为这些是有状态的 bean,如果我得到相同的对象,我最终会遇到并发问题)。

这是旧的实现:

@Service
public class Service {

@Autowired
private List<HandlersInterface> handlers;

public void run() {
    // handle the action using one of the handlers
    handlers.get(0).doSomething();
}

这很好用,但是每次我调用 service.run() 时,处理程序列表都是相同的,因此同一个处理程序可能会运行多次而导致问题。

转到 spring 查找方法注入,我找到了一些简单场景的教程,但我找不到管理我拥有的整个列表的东西。比如:

@Service
public class Service {

public void run() {
List<HandlersInterface> handlers= lookUpHandlers();   
handlers.get(0).doSomething();
}

@Lookup
protected List<AppDataMessageHandler> lookUpHandlers() {
    return null; //I want this to be replaced by spring to provide a list of PROTOTYPE beans
}

}

想知道我是否应该在我的 spring.xml 文件中添加列表? (注意我的列表是不同@Component bean的列表,实现了一个通用接口)

【问题讨论】:

    标签: java spring concurrency


    【解决方案1】:

    我的最终解决方案是:

    spring.xml

      <util:list id="test" scope="prototype" value-type="CommonInterfaceOfBeans">
            <ref bean="bean1ClassName"/>
            <ref bean="bean2ClassName"/>
            <ref bean="bean3ClassName"/>
            <ref bean="bean4ClassName"/>
            <ref bean="bean5ClassName"/>
        </util:list>
    

    在我的课堂上:

    @Service
    public class Service {
    
    public void run() {
    List<CommonInterfaceOfBeans> handlers= lookUp();   
    handlers.get(0).doSomething();
    }
    
      @Lookup(value = "test")
        protected List<CommonInterfaceOfBeans> lookUp() {
            return null; //This gets replaced with list by Spring via cglib.
        }
    

    如果不在 spring.xml 中手动定义一个列表,我找不到做同样事情的方法

    【讨论】:

      猜你喜欢
      • 2015-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 2011-05-01
      相关资源
      最近更新 更多