Manually creating a JNDI DataSource using Spring

Some time ago, we created an application that renders reports using Eclipse BIRT. To make the DataSource of the BIRT reports configurable, we decided to use JNDI (BIRT has build-in support for that). Everything worked fine, but then we should make one part of the application runnable as ANT task.

We had two possibilities to solve that:

  1. Exchange the DataSource programatically
  2. Somehow provide a DataSource via JNDI

Solution 1 seemed to be a little bit hacky, so we looked for an simple possibility to manually provide a JNDI DataSource.

Our Solution was to use Spring-JDBC to create a DataSource and Spring-test to publish it into the JNDI Context:

SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
DriverManagerDataSource dataSource = new DriverManagerDataSource(url, username, password);
dataSource.setDriverClassName(driverClassName);
builder.bind("java:comp/env/jdbc/MyDB", dataSource);
try {
    builder.activate();
} catch (Exception e) {
    e.printStackTrace();
}

To run this in the context of our own ANT Task, we needed an additional thing before initializing the JNDI Context:

Thread.currentThread().setContextClassLoader(MyAntTask.class.getClassLoader());

That’s because ANT creates a custom ClassLoader for tasks declared in the build.xml like that:


    
        
        
        
    
Short URL for this post: http://wp.me/p4nxik-V2
This entry was posted in Spring Universe and tagged , , , , . Bookmark the permalink.

Leave a Reply