How to specify name for resource annotations in compile time?

蹲街弑〆低调 提交于 2019-12-09 12:26:57

问题


Our code has something like this:

@Resource(name = "java:comp/resource/foo/bar/ONE_QUEUE")
private Queue queue;

However, in one deployment scenario the queue annotation should look like this:

@Resource(name = "java:comp/resource/foo/bar/SECOND_QUEUE")
private Queue queue;

I would like to choose the name to use with Maven build profiles.

What options do I have?


回答1:


This is not the right way to do things. Resources should be added to the local jndi name of individual EJBs. This is to separate the jndi name used in the bean code from the global jndi bindings set by the bean deployer. The mapping of the bean local jndi binding and the global binding may be handled via the ejb-jar.xml and appserver-specific deployment descriptors.

So, instead, you should declare your @Resource (which is equivalent to a <resource-ref> element indicating resource reference name and type) like this:

@Resource(name = "jms/queue/aQueue")
private Queue queue;

Then, in a appserver-specific deployment descriptor (for GlassFish it's sun-ejb-jar.xml, for JBoss it's jboss.xml, for WebLogic it's weblogic-ejb-jar.xml, etc), declare a <resource-ref> element indicating the resource reference name and the global jndi binding via the <jndi-name> element.

<resource-ref>
  <res-ref-name>jms/queue/aQueue</res-ref-name>
  <jndi-name>resource/foo/bar/ONE_QUEUE</jndi-name>
</resource-ref>

Once you'll get the whole thing working, it will be easy to variabalize this appserver-specific deployment descriptor using Maven for different environments with profiles and filtering. Just use a property, activate filtering of resources, and set different value in profiles. Something like that:

<resource-ref>
  <res-ref-name>jms/queue/aQueue</res-ref-name>
  <jndi-name>${my.jndi.name}</jndi-name>
</resource-ref>



回答2:


I think you can use maven filtering, although it would feel strange.

Here is an article about this approach.




回答3:


If you don't want to do per-bean config, you could use the JBoss Seam functionality for this (see Seam reference doc). I don't know if this is part of Java Dependency Injection specification (JSR-299) (if you worry about vendor independence).

EDIT: Apparently it is part of JSR-299, see resin's doc about JSR-299



来源:https://stackoverflow.com/questions/2084602/how-to-specify-name-for-resource-annotations-in-compile-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!