【问题标题】:Inject JNDI resources into a collection property of EJB将 JNDI 资源注入到 EJB 的集合属性中
【发布时间】:2015-07-03 13:35:01
【问题描述】:

我有一个无状态的 EJB,其中包含应该注入的多个 JNDI 资源:

@Stateless(name = "QueueDispatcher")
public class QueueDispatcher {  
    @Resource(name = "jms/syncQueue1")
    private Queue queue1;    
    @Resource(name = "jms/syncQueue2")
    private Queue queue2;
    ...

    private List<Queue> queueList;  

    @PostConstruct
    public void init() {
        //Move injected queues into arraylist...
        queueList = new ArrayList<Queue>();
        if(queue1 != null){ queueList.add(queue1); }
        if(queue2 != null){ queueList.add(queue2); }
        ...
    }
}

我当前的实现使用多个字段来接收注入的资源,然后将它们移动到一个集合中以供后续使用。

但是,这段代码很难看,队列的数量应该是动态的。当我必须增加队列数量时,我不想在多个地方更改代码,而是简单地添加单个配置行/注释。

有没有办法配置无状态bean,以便将资源直接注入到列表中?我正在使用 EJB 3.0。

【问题讨论】:

    标签: dependency-injection resources ejb jndi


    【解决方案1】:

    @Resource 不能绑定到列表,但您可以使用包含所有资源的字符串列表,例如 jms/syncQueue2,jms/syncQueue2,然后在 @PostCostruct 中进行动态查找。

    @Resource(name = "myqueues")
    private String queues;
    
    ...
    
    @PostConstruct
    public void init() {
        Context ctx=new InitialContext();
        String[] list = queues.split(",");
        for(String item : list) {
            try { 
                Queue q = (Queue) ctx.lookup(item);
                queueList.add(q);
            }
        }
    }
    

    使用 catch ecc 完成代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多