views:

447

answers:

2

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:

  1. 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.
  2. 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?).

+2  A: 

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>
oxbow_lakes
I should have mentioned this in the post. I am writing a component which will be running in a web app, but I would like to also be able to invoke it from plain Java SE command line apps and JUnit tests.My initial idea was that I should be able to setup the necessary environment (JNDI, DBCP, JTA) so that the component code can always rely on these.I'm reluctant to introduce a whole new framework such as Spring into the application, but that could be an option. Are there specific Spring documentation pages relating to this that you would recommend?
nikita
I've edited the answer to provide a link and some indication of what to do. Spring JDBC is very powerful
oxbow_lakes
Thank you for the details. I don't have enough points to mark the answer as helpful :|
nikita
+1  A: 

These references are pretty old but may help to use jnpserver (JBoss Naming Service provider):

Pascal Thivent