java - 使用 Spring JdbcTemplate - 注入(inject)数据源与 jdbcTemplate

标签 java spring dependency-injection jdbctemplate

根据 Spring documentation , 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 是在 Component 类中使用数据源的 setter 创建的。

这样做有什么问题吗?而不是在应用程序中只有一个 jdbcTemplate 实例?

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

然后将 jdbcTemplate 本身直接注入(inject)到组件中

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


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

jdbcTemplate本身不能直接注入(inject)组件类有什么原因吗?

SGB

最佳答案

你可以做你想做的事。 The javadoc of JdbcTemplate甚至说得很清楚:

Can be used within a service implementation via direct instantiation with a DataSource reference, or get prepared in an application context and given to services as bean reference.

关于java - 使用 Spring JdbcTemplate - 注入(inject)数据源与 jdbcTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17868096/

相关文章:

java - 找到由给定数字整除的两位数字组成的最小数字

java - Cloudera 向导步骤 "Install Agent"期间的 SSH 问题

php - Laravel setter 注入(inject)

c# - Structuremap类库模块

spring - 自定义 WebSecurityConfigurerAdapter

.net - 使用外部 DLL 的 DI

java - 迁移到 64 位 JVM 的经验

java - 识别 ISO 8601 中的时区

java - 存储库中的 deleteAll() 随机导致 ConstraintViolationException

java - 为什么 Spring 数据(JPA)的删除方法没有返回值?