Nov 08 2012

Learning Spring, part VI

Category: TechnicalIuliana @ 15:44

This won’t be a post  about a problem or a question, but about an observation.

When I took the spring Core course in Belgrade this June, in the Chapter about data access the jdbcTemplate instance was created like this:
Java code:

//random DAO class
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
}

Xml configuration:

<bean id="dataSource" class="..." />

After that I read Spring in Action, then the Spring reference and everywhere when given an example on how to use jdbcTemplate, the instance was created and injected like that.

And I am confused. If jdbcTemplate instance is thread-safe once configured, is recommended to not create one for each use and is stateless (does not maintain any conversational state) why don’t we just create it as a singleton bean and use it as such?
Sample of my code:

//random DAO class
private JdbcTemplate jdbcTemplate;
@Autowired
@Qualifier("jdbcTemplate")
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}

Xml configuration:

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

Tags: ,

Leave a Reply