如何以编程方式使用Spring的JdbcTemplate? [英] How to programmatically use Spring's JdbcTemplate?

查看:92
本文介绍了如何以编程方式使用Spring的JdbcTemplate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用Spring的 JdbcTemplate ,它是通过Spring配置进行配置的,如下所示。有没有办法在不注入数据源的情况下做到这一点?我想以编程方式创建 JdbcTemplate 实例,并使用 TheOracleDS 初始化数据源。

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.

我们当前的配置:

Java类

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数据源配置

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






更新:原因我问这是我不是依赖注入/让Spring管理bean的总信徒。


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

推荐答案

只用原始的JNDI查找:

Just use a raw JNDI lookup:

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

这篇关于如何以编程方式使用Spring的JdbcTemplate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆