How to programmatically use Spring's JdbcTemplate?

倖福魔咒の 提交于 2019-12-21 01:57:11

问题


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


回答1:


Just use a raw JNDI lookup:

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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/1779200/how-to-programmatically-use-springs-jdbctemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!