简体   繁体   中英

Dynamic resource injection in EJB3?

I know how to do resource injection to get JMS queue in EJB, just like the following sample, it's easy to get QUEUE1. But if I have lots of queue, and I don't want to change code when there is a new queue "QUEUE4".

Is it possible to get the resource dynamically or any suggestion for it?

@Stateless
public class OrderBean implements Order {

@Resource(name = "A.QCF", mappedName = "A.QCF")
private ConnectionFactory connectionFactory;

@Resource(name = "QUEUE1")
private Queue QUEUE1;

@Resource(name = "QUEUE2")
private Queue QUEUE2;

@Resource(name = "QUEUE3")
private Queue QUEUE3;

    public String sendData(String abc) {
        // ...
    }
}

Update:

Thanks for Gonzalo and bkail, the following is my solution:

EJB code: "QueueName" is a parameter from client.

InitialContext initialContext = new InitialContext();
Queue dynamicQueue = (Queue)initialContext.lookup("java:comp/env/" + QueueName);

ejb-jar.xml:

<enterprise-beans>
    <session>
        <<resource-env-ref>>
            <resource-env-ref-name>Queue1</resource-env-ref-name>
            <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>
        </<resource-env-ref>>
        <<resource-env-ref>>
            <resource-env-ref-name>Queue2</resource-env-ref-name>
            <resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>
        </<resource-env-ref>>
    </session>
</enterprise-beans>

When I have a new queue, I just need to change ejb-jar.xml and restart server.

I am afraid you'd have to do a explicit JNDI lookup so that you can dynamically set the resource you want to inject. Something like:

Queue dynamicQueue = (Queue)initialContext.lookup(dynamicQueueName);

where dynamicQueueName is the variable you set depending on whatever criteria you are using to figure out the queue name.

If I understand correctly, you want to dynamically declare a resource-env-ref for a Queue (which is basically what the @Resource is doing). That doesn't make sense:

Jetty: adding <resource-env-ref> programmatically

READERS, there must be a more elegant answer than mine.

A static parametrisable initialisation, for instance from a resource bundle (.properties) file, can be done. See Andy Gibson . (Resource bundles are cached by the way, but you can flush the cache.)

I think you might mean having one object sending to a one out of a dynamic set of queues. Personnally I would inject my own Queue Provider bean, self programmed. Look at Reconfigure your application at runtime with reloadable property files .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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