使用Spring JdbcTemplate——注入数据源 vs jdbcTemplate

39

根据Spring 文档,使用Spring JdbcTemplate的步骤如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd">

        <!-- Scans within the base package of the application for @Components to configure as beans -->
        <context:component-scan base-package="org.springframework.docs.test" />

        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="${jdbc.driverClassName}"/>
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        </bean>

        <context:property-placeholder location="jdbc.properties"/>

    </beans>

然后,

    @Repository
    public class JdbcCorporateEventDao implements CorporateEventDao {

        private JdbcTemplate jdbcTemplate;

        @Autowired
        public void setDataSource(DataSource dataSource) {
            this.jdbcTemplate = new JdbcTemplate(dataSource);
        }

        // JDBC-backed implementations of the methods on the CorporateEventDao follow...
    }

基本上,JdbcTemplate是在组件类中使用数据源的setter方法创建的。

这样做有什么问题吗?这样做能确保应用程序中只有一个JdbcTemplate实例。

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
    p:dataSource-ref="dataSource" 
/>

然后直接将jdbcTemplate注入到组件中

@Repository
public class JdbcCorporateEventDao implements CorporateEventDao {
    @Resource("jdbcTemplate")
    private JdbcTemplate jdbcTemplate;


    // JDBC-backed implementations of the methods on the CorporateEventDao follow...
}

为什么jdbcTemplate本身不能直接注入到组件类中?

SGB


可能是 https://dev59.com/AGox5IYBdhLWcg3wDgTR 的重复问题。但是这个问题还没有得到解答。 - SGB
4个回答

34

你可以按照自己的意愿去做。 JdbcTemplate的javadoc 甚至清楚地说明了这一点:

可通过直接实例化DataSource参考,在服务实现中使用,或在应用程序上下文中准备并作为bean参考提供给服务。


3
谢谢你的链接和简洁明了的回答,以及引用Javadoc的语句。这个问题困扰我已经有一段时间了——因为我在网上看到的所有示例似乎都是注入数据源,这让我想知道是否我漏掉了什么... - SGB
这些都是微妙的细节,春天可能会误导很多人,如果有人没能看出其中的玄机,比如我。 - pramodc84

29
在spring-context.xml文件中添加以下内容。
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
</bean>

你可以通过自动连线直接使用jdbcTemplate,如下:

  @Autowired JdbcTemplate jdbcTemplate;

示例:

this.jdbcTemplate.query("select * from ******",new RowMapper());

1
如何为多个数据源执行相同的操作?我可以这样指定:<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource1"/> </bean>,并且为另一个数据源指定:<bean id="jdbcTemplate2" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource2"/> </bean>。这是将多个数据源设置到JDBC模板的正确方式吗? - Analysts
1
@分析师们,您应该为每个数据源定义一个单独的jdbcTemplate。因此,如果您有2个数据源,则会为datasource1定义jdbcTemplate1,为datasource2定义jdbcTemplate2。并根据需要将jdbcTemplates分别注入到服务层中。 - SGB
@SCB所说的是对的,你必须为多个数据库拥有多个bean。 - Odaiah

5
您也可以这样做
@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = { 
    ServiceMarker.class,
    RepositoryMarker.class }
)
public class AppConfig {

    /**
     * To resolve ${} in @Values, you must register a static PropertySourcesPlaceholderConfigurer in either XML or 
     * annotation configuration file.
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

持久化配置

@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {

    @Autowired
    private Environment env;

 /**
  * The @Bean annotation is used to declare a Spring bean and the DI requirements. The @Bean annotation is equivalent to
 *  the <bean> tag, the method name is equivalent to the id attribute within the <bean> tag.
  * 
  * <bean id="mySqlDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close" 
        p:driverClassName="${jdbc.mysql.driverClassName}" 
        p:url="${jdbc.mysql.url}"   
        p:username="${jdbc.mysql.username}" 
        p:password="${jdbc.mysql.password}" />
  * 
  * @return
  */
     @Bean(destroyMethod = "close")
     public DataSource mySqlDataSource() {
         BasicDataSource dataSource = new BasicDataSource();
         dataSource.setDriverClassName(env.getProperty("jdbc.mysql.driverClassName"));
         dataSource.setUrl(env.getProperty("jdbc.mysql.url"));
         dataSource.setUsername(env.getProperty("jdbc.mysql.username"));
         dataSource.setPassword(env.getProperty("jdbc.mysql.password"));
         return dataSource;
     }

     @Bean(destroyMethod = "close")
     public DataSource ls360DataSource() {
         BasicDataSource dataSource = new BasicDataSource();
         dataSource.setDriverClassName(env.getProperty("jdbc.ls360.driverClassName"));
         dataSource.setUrl(env.getProperty("jdbc.ls360.url"));
         dataSource.setUsername(env.getProperty("jdbc.ls360.username"));
         dataSource.setPassword(env.getProperty("jdbc.ls360.password"));
         return dataSource;
     } 
}

MySqlDaoImpl

@Repository
public class MySqlDaoImpl implements MySqlDao{

    private static final Logger logger = LogManager.getLogger();

    @Inject
    private DataSource mySqlDataSource;
    private JdbcTemplate mySqlJdbcTemplate;

    @PostConstruct
    public void afterPropertiesSet() throws Exception {
        if (mySqlDataSource == null) {
            throw new BeanCreationException("Must set mySqlDataSource on " + this.getClass().getName());
        }
        this.mySqlJdbcTemplate = new JdbcTemplate(mySqlDataSource);
    }

    @Override
    public void callStoredProcedure(String storedProcedureName, Map<String, Object> inParamMap) throws Exception {

        SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(mySqlJdbcTemplate).withProcedureName(storedProcedureName);
        SqlParameterSource in = new MapSqlParameterSource(inParamMap);

        logger.info("Calling stored Procedure: " + storedProcedureName);
        Map<String, Object> simpleJdbcCallResult = simpleJdbcCall.execute(in);
        logger.info("Stored Procedure Result: " + simpleJdbcCallResult);
    }
}

主要

public static void main(String[] args ) {
    try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
        MySQLDao mySqlDao = springContext.getBean(MySQLDaoImpl.class);
        try {
            Map<String, Object> inParamMap = new HashMap<String, Object>();
            inParamMap.put("iCourseId", 1);
            mySqlCourseRenewalDao.callStoredProcedure("usp_processCourseRenewal", inParamMap);
        } catch (Exception e) {
            logger.error("Exception occurs", e);
        }
    } catch (Exception e) {
        logger.error("Exception occurs in loading Spring context: ", e);
    }
}

谢谢


0

在替代底层DataSource时,使用和共享JdbcTemplate没有技术上的问题。

然而,共享JdbcTemplate存在一些设计缺陷,这可能会更倾向于注入DataSource

  • 使用JdbcTemplate是DAO的实现细节,我们希望将这些细节隐藏起来
  • JdbcTemplate很轻量级,因此为了效率而共享它可能是一种过早的优化
  • 共享JdbcTemplate并不是没有风险的,因为它具有一些可变状态(除了底层DataSource中的可变状态)

这是假设JdbcTemplate在其默认配置(fetchSizemaxRows等)下使用的典型情况。如果需要配置,则可能会驱动设计朝特定方向发展,例如从上下文注入共享的预配置JdbcTemplate,或者由单个DAO拥有的多个JdbcTemplate实例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接