How to programmatically use Spring's JdbcTemplate?

Not sure why you want to do that but... you could lookup the JDNI datasource with Spring's JndiDataSourceLookup:

JndiDataSourceLookup lookup = new JndiDataSourceLookup();
lookup.setResourceRef(true); // if the lookup occurs in a J2EE container
DataSource ds = lookup.getDataSource(jndiName);

Or just perform a "manual" lookup using Sun's classes:

Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("jdbc/AcmeDB");

Then, just pass the datasource reference to the JdbcTemplate constructor or call setDataSource(ds).

But, as I said, I have no idea why you don't want to use injection.


Here's some sample code from a project I've written:

SimpleJdbcTemplate db;
DataSource dataSource = new SingleConnectionDataSource(System.getProperty(
         "lingcog.db.connectstring"),
      System.getProperty("lingcog.db.username"),
      System.getProperty("lingcog.db.password"), false);

db = new SimpleJdbcTemplate(dataSource);

Maybe my code would be simpler if I used injection, but this is a good example of how to do this without using injection.

You can use an org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup object to find the data source you want by JDNI name.

DataSource dataSource = new JndiDataSourceLookup().getDataSource("java:/TheOracleDS")
SimpleJdbcTemplate db=new SimpleJdbcTemplate(dataSource);

Just use a raw JNDI lookup:

public void setDataSourceName(String name) {
    InitialContext ctx = new InitialContext();
    jdbcTemplate = new JdbcTemplate((DataSource) ctx.lookup(name));
}