Search code examples
javaspringoopabstract-classjdbctemplate

Extending a java spring singleton abstract class with JdbcTemplate field


I am looking at this code base and I am trying to understand how it works or if it has code smell.

@Repository
@Scope("singleton")
public abstract class BaseDao {

  @Autowired
  protected JdbcTemplate jdbc;

}
@Repository
@Scope("singleton")
public class Dao1 extends BaseDao {

}

@Repository
@Scope("singleton")
public class Dao2 extends BaseDao {

}

My question is what happens when I extend the BaseDAO abstract class in Dao1 & Dao2, does spring create 2 jdbc templates, one for both, Dao1 & Dao2 or because BaseDAO is spring-singleton (I am aware this is different from Java singleton or singleton design pattern), it uses/shares the same jdbc template with all child classes once any child has created a jdbc template.

Would spring create a new jdbctemplate each time you use @Autowired protected JdbcTemplate jdbc or the same one?

EDIT: updated the question to remove confusing mentions of session.


Solution

  • @JB Nizet's comment above is the right answer, spring by default uses singleton scope and hence it would inject the same JdbcTemplate in both the classes, Dao1 & Dao2.