0

I have OracleConfiguration class where i have the DataSource and Jdbctemplate defined .Below is the code snippet

@Configuration
//@ConfigurationProperties("oracle")
@PropertySource("classpath:dev.properties")
public class OracleConfiguration {
     //omitted variable names,getters n setter for brevity
DataSource dataSource() throws SQLException {

    OracleDataSource dataSource = new OracleDataSource();
    dataSource.setDriverType(driverType);
    dataSource.setUser(username);
    dataSource.setPassword(password);
    dataSource.setURL(url);
    dataSource.setImplicitCachingEnabled(true);
    dataSource.setFastConnectionFailoverEnabled(true);
    return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.setResultsMapCaseInsensitive(true);
    return jdbcTemplate;
}

Now to connect to database in every repository i create one instance of JdbcTemplate and annotate it with Autowire which works fine .

@Component
public class RolesDaoImpl  implements RolesDao  {

    @Autowired
    private JdbcTemplate jdbcTemplate;  
    // works fine able to perform jdbc operations

But i read there should be only one instance of JdbcTemplate per Database schema .So how can i make this JdbcTemplate code generic.I tried the below but i am not able to connect to Db using the below technique

public class JdcTemplateDaoImpl {
   private JdbcTemplate jdbcTemplate; //SETTER NOT REQUIRED 

public JdbcTemplate getJdbcTemplate() {

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

And my every other DaoImpl can extend this JdcTemplateDaoImpl .How can i achieve it?

Raj R
  • 63
  • 1
  • 3
  • 11
  • It's exactly as Mark says. The last snippet is totally superfluous. You can even think about injecting the `JdbcTemplate` into an AbstractDao and make it protected. There's no need to inject it into every single `Impl` you have. – Jan B. Sep 16 '18 at 21:06

1 Answers1

1

From the posted configurations, it looks like the JdbcTemplate is a singleton bean (scope singleton is a default scope in spring).

So, there is one instance of JdbcTemplate type in the application context and it gets injected into repositories. Place a breakpoint in different repositories and the chances are that you'll see that the instance is the same (the same address in memory).

So the technique presented in the last code snippet is not required

Why do you think that it's not the same instance?

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97