Out of container JNDI data source

datasource, java, jndi

Solution

Why are you using JNDI for this? It's not that it's a bad solution if you have a provider but there are alternatives such as dependency injection (IoC: via Spring or Guice).

The Spring JDBC data access is described here. The great thing is that you can use Spring to inject a `DataSource` into your code:

<bean class="com.my.Persister">
    <property name="dataSource" ref="dataSource" />
</bean>

The data source can be defined using a JNDI-lookup:

<jee:jndi-lookup id="dataSource" jndi-name="jdbc/MyDataSource" /> 

In a test environment, you could inject the data source directly:

<bean id="dataSource" class="apache.db.PoolingDataSource">
    <!-- config goes here -->
</bean>

Problem

I would like to configure a DataSource using JNDI in a Java SE app. What is the best way to do this? So far, I've come across 2 projects: - Apache Naming. The project page has a specific example for configuring a data source, but it looks like the project is super old and no longer active. - JBossNS. It looks like it's easy to configure a local-only JNDI using `LocalOnlyContextFactory`, but I haven't found any docs on how to actually configure a data source. If possible, I would like to also configure the data source with a JTA transaction manager (using JOTM?).

Original source