Spring 使用JdbcTemplate的单个实例
我有OracleConfiguration类,其中定义了数据源和JdbctemplateSpring 使用JdbcTemplate的单个实例,spring,spring-mvc,jdbctemplate,Spring,Spring Mvc,Jdbctemplate,我有OracleConfiguration类,其中定义了数据源和Jdbctemplate @Configuration //@ConfigurationProperties("oracle") @PropertySource("classpath:dev.properties") public class OracleConfiguration { //omitted variable names,getters n setter for brevity DataSource data
@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;
}
现在连接到每个存储库中的数据库,我创建了一个实例
JdbcTemplate,并使用Autowire对其进行注释,效果良好
@Component
public class RolesDaoImpl implements RolesDao {
@Autowired
private JdbcTemplate jdbcTemplate;
// works fine able to perform jdbc operations
但是我读到每个数据库模式应该只有一个JdbcTemplate实例。因此,如何使此JdbcTemplate代码通用。我尝试了下面的方法,但无法使用下面的技术连接到数据库
public class JdcTemplateDaoImpl {
private JdbcTemplate jdbcTemplate; //SETTER NOT REQUIRED
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setDataSource ( DataSource dataSource )
{
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
我的every other DaoImpl可以扩展这个JdcTemplateDaoImpl。我如何实现它?从发布的配置来看,
JdbcTemplate
似乎是一个单例bean(scope singleton是spring中的默认作用域)
因此,在应用程序上下文中有一个JdbcTemplate类型的实例,它被注入到存储库中。
在不同的存储库中放置一个断点,您很可能会看到实例是相同的(内存中的相同地址)
因此,不需要上一个代码片段中介绍的技术
为什么你认为这不是同一个例子?这正是马克所说的。最后一个片段是完全多余的。您甚至可以考虑将
JdbcTemplate
注入AbstractDao并使其受到保护。没有必要将它注入到您拥有的每一个Impl
。