Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically use Spring's JdbcTemplate?

We use Spring's JdbcTemplate which is configured through Spring config as illustrated below. Is there a way to do this without injecting the data source? I'd like to just create the JdbcTemplate instance programmatically and "initalize" the datasource using TheOracleDS.

Our current config:

Java class

private JdbcTemplate jdbcTemplate;

@Resource(name = "myDataSource")
public void setDataSource(DataSource dataSource) {
     this.jdbcTemplate = new JdbcTemplate(dataSource);
}

Spring config

<jee:jndi-lookup id="myDataSource" jndi-name="java:/TheOracleDS"/>

Oracle datasource config

<xa-datasource>
      <jndi-name>TheOracleDS</jndi-name>
      ...
</xa-datasource>

Update: Reason I'm asking this is I'm not a total believer in dependency injection / having Spring manage beans..

like image 766
Marcus Leon Avatar asked Nov 22 '09 16:11

Marcus Leon


3 Answers

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);
like image 61
Ken Bloom Avatar answered Oct 31 '22 21:10

Ken Bloom


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.

like image 6
Pascal Thivent Avatar answered Oct 31 '22 21:10

Pascal Thivent


Just use a raw JNDI lookup:

public void setDataSourceName(String name) {
    InitialContext ctx = new InitialContext();
    jdbcTemplate = new JdbcTemplate((DataSource) ctx.lookup(name));
}
like image 3
oxbow_lakes Avatar answered Oct 31 '22 21:10

oxbow_lakes