从 java.sql.Connection 实例化 JdbcTemplate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3108710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 00:24:31  来源:igfitidea点击:

Instantiating a JdbcTemplate from a java.sql.Connection

javaspringconnectiondatasourcejdbctemplate

提问by Bozho

I want to obtain a JdbcTemplatein my Java code. I've already got a working java.sql.Connection. To create a new JdbcTemplateit would normally need an instance of the javax.sql.DataSourceinterface.

我想JdbcTemplate在我的 Java 代码中获得一个。我已经有工作了java.sql.Connection。要创建一个新的,JdbcTemplate它通常需要一个javax.sql.DataSource接口实例。

Is it somehow possible to obtain a new JdbcTemplatefrom an existing java.sql.Connection?

是否有可能JdbcTemplate从现有的获得新的java.sql.Connection

回答by Bozho

Technically, you can, using SingleConnectionDataSource

从技术上讲,您可以使用 SingleConnectionDataSource

new JdbcTemplate(new SingleConnectionDataSource(connection, false))

new JdbcTemplate(new SingleConnectionDataSource(connection, false))

However, this is not quite advisable, unless for unit-tests for example.

然而,这不是很可取,除非例如单元测试。

You'd better use a full-featured DataSourceand wire things using spring.

你最好用一个功能齐全的DataSource用弹簧线的东西。

回答by duffymo

No, JdcbTemplate is a Spring class; Connection is part of the JDK. Connection knows nothing about JdbcTemplate.

不,JdcbTemplate 是一个 Spring 类;连接是 JDK 的一部分。Connection 对 JdbcTemplate 一无所知。

The way to do it is to add a JdbcTemplate bean in your Spring app context; then inject it into the classes that need it declaratively.

这样做的方法是在您的 Spring 应用程序上下文中添加一个 JdbcTemplate bean;然后以声明方式将其注入到需要它的类中。