A-D
A-D

Reputation: 37

Autowiring JdbcTemplate vs Datasource?

Which would be the right/better practice when implementing non-jpa/orm DAO layers?

@Repository
public class SampleDao {

    private JdbcTemplate jdbcTemplate;

    public SampleDao(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    // --- OR ---

    public SampleDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

}

Upvotes: 1

Views: 1321

Answers (1)

Phil Webb
Phil Webb

Reputation: 8622

In a Spring Boot application I'd generally recommend injecting JdbcOperations rather than injecting the JdbcTemplate or creating a new JdbcTemplate instance from the DataSource. The JdbcOperations interface is implemented by the auto-configured JdbcTemplate.

The reasons are as follows:

  • The bean is already defined, so there's one less object instance
  • JdbcOperations doesn't surface any setters so you can't accidentally change things on the shared singleton bean
  • You can use spring.jdbc.template... application properties to configure it
  • It's easier to mock than DataSource if you need to do so for testing

Upvotes: 1

Related Questions