I'm trying to figure out how to use constructor injection in CDI where one of the parameters is a JNDI lookup.
With normal field injection, I can do the following:
@Stateless
public class Publisher
{
@Inject
@JMSConnectionFactory("java:/jms/remoteCF")
private JMSContext context;
@Resource(lookup="java:global/remote")
private InitialContext externalContext;
private Topic genericTopic;
@PostConstruct
public void init(){
try {
Object obj = externalContext.lookup(TOPIC);
genericTopic = (javax.jms.Topic) obj;
} catch (NamingException namingException) {
}
}
}
However, I would like to switch this bean to constructor injection. Unfortunately, I cannot figure out how to create a constructor which injects my externalContext
resource, given that it is a JNDI lookup.
Example:
@Inject
public Publisher( @JMSConnectionFactory("java:/jms/remoteCF") JMSContext context, @Resource( "java:global/remote") InitialContext externalContext ){
this.context = context;
this.externalContext = externalContext;
}
But @Resource
is not an allowable annotation as a parameter.
How can I specify that the externalContext
parameter is a bean retrieved via a JNDI lookup? Where do I specify the JNDI name?
You have two options.
@Produces
@Named(TOPIC)
public Topic findTopic(JMSContext context) {
return context.createTopic(TOPIC);
}
and then inject that into your constructor
InitialContext
.
@Produces
@Named("someName")
@Resource("java:global/remote")
private InitialContext externalContext;