You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需编写DataSource配置,创建NamedParameterJdbcTemplate单例Bean

解决方案:无需手动配置DataSource,轻松实现NamedParameterJdbcTemplate单例Bean

完全可以不用手动编写SQLServerDataSource这类实例化代码,甚至连自定义的DatabaseConfig配置类都可以省掉,Spring Boot的自动配置已经帮你搞定了所有事情,具体如下:

核心原理

当你引入spring-boot-starter-jdbc依赖,并且在application.properties中配置了spring.datasource.*相关属性后,Spring Boot会自动完成:

  • 读取配置创建单例的DataSource Bean
  • 基于该DataSource自动创建单例的NamedParameterJdbcTemplate Bean

最优精简实现

直接保留你最初的代码即可,完全满足需求:

1. 保持application.properties配置不变

spring.datasource.url= jdbc:sqlserver://localhost;encrypt=true;databaseName=Test
spring.datasource.username= sauser
spring.datasource.password= sauserpw

2. 保留Repository的注入方式

@Repository
public class CustomerRepositoryImpl implements CustomerRepository {

    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    // 构造函数注入(推荐方式)
    public CustomerRepositoryImpl(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }

    // 你的业务方法...
}

此时注入的NamedParameterJdbcTemplate就是Spring容器管理的单例Bean,多个Repository注入的都是同一个实例,完全避免重复创建。

若需自定义配置(可选)

如果确实需要对NamedParameterJdbcTemplate做自定义配置(比如设置特定属性),只需编写配置类,但依然不需要手动创建DataSource:

@Configuration
public class DatabaseConfig {
    
    // 直接注入Spring自动创建的DataSource
    @Bean
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate(DataSource dataSource) {
        NamedParameterJdbcTemplate template = new NamedParameterJdbcTemplate(dataSource);
        // 这里可以添加自定义配置,比如设置查询超时等
        return template;
    }
}

注意:Repository依然直接注入NamedParameterJdbcTemplate,而不是注入DatabaseConfig后手动调用方法(手动调用会创建新实例,破坏单例特性)。


内容的提问来源于stack exchange,提问作者mattsmith5

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 14:32:55