So, I read several times that if you use a Java EE container, you do not need to add environment params to an InitialContext
in order to be able to use JNDI.
So I tried this:
@Bean
public DataSource dataSource() {
JndiDataSourceLookup jndiDataSourceLookup = new JndiDataSourceLookup();
return jndiDataSourceLookup.getDataSource("java:global/ExpensesDataSource");
}
However, retrieving a datasource using JNDI like this gives me a NoInitialContextException
, telling me to specify the environment params.
Now, okay, so seems I was wrong to think it would work so flawlessly, so I tried retrieving the datasource like this:
@Bean
public DataSource dataSource() {
Properties jndiProperties = new Properties();
jndiProperties.setProperty(Context.PROVIDER_URL, "jnp://localhost:1099");
jndiProperties.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
jndiProperties.put("java.naming.factory.url.pkgs", "org.jboss.naming.org.jnp.interfaces");
JndiDataSourceLookup jndiDataSourceLookup = new JndiDataSourceLookup();
jndiDataSourceLookup.setJndiEnvironment(jndiProperties);
return jndiDataSourceLookup.getDataSource("java:global/ExpensesDataSource");
}
However this gives me a javax.naming.CommunicationException: Failed to connect to server localhost:1099
I've also tried just using localhost:1099
or localhost
, none of them worked.
So my question is: do I even need to specify these properties, since JBoss 8 is a Java EE container to my knowledge. And if so, what provider url do I need to specify here?
If you use javax.naming.InitialContext, you don't need to specify environment params, just like you said. For example:
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:jboss/datasources/ExampleDS");
Not sure how JndiDataSourceLookup works..
For looking up a datasource, you can inject it using @Resource (inside an ejb context)
@Resource(name= "java:jboss/datasources/ExampleDS")
private Datasource ds;
Hope it helps!