Skip to content
Advertisement

using Spring JdbcTemplate – injecting datasource vs jdbcTemplate

As per Spring documentation, the steps to use Spring JdbcTemplate is as follows:

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

And then,

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

Basically, the JdbcTemplate is created inside the Component class using the setter for datasource.

Is there anything wrong with doing it this way instead so that there is exactly ONE instance of jdbcTemplate in the application?

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

And then injecting the jdbcTemplate itself directly into the Component

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


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

Is there a reason why the jdbcTemplate itself must not be injected into the component class directly?

SGB

Advertisement

Answer

You can do what you want. The javadoc of JdbcTemplate even clearly says it:

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement