开发者

How to programmatically use Spring's JdbcTemplate?

开发者 https://www.devze.com 2022-12-12 08:55 出处:网络
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 insta

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..


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);


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.


Just use a raw JNDI lookup:

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

精彩评论

暂无评论...
验证码 换一张
取 消