Java 创建 JDBCTemplate Singleton Bean,无需编写数据源

问题描述 投票:0回答:1

我正在尝试使 JdbcTemplate 成为 Singleton Bean,而不是在多个存储库中调用它。

在当前的代码库中,我什至不需要编写 DataSource 配置。

对于我的新代码单例配置 Bean 尝试,有没有一种方法可以设置 JDBCTemplate,而无需通过 DataSource 配置?

当前代码:

@Repository
public class CustomerRepositoryImpl implements CustomerRepository {

    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    public CustomerRepositoryImpl(NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }

}

它将使用 application.properties 文件自动读取数据源

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

新代码尝试:

@Configuration
public class DatabaseConfig {
    
    @Bean
    public NamedParameterJdbcTemplate namedParameterJdbcTemplate(DataSource dataSource)
    {
        return new NamedParameterJdbcTemplate(dataSource);
    }
}

// trying to prevent writing this code in for Datasource if possible, and importing a new maven package com.microsoft.sqlserver.jdbc.SQLServerDataSource;

SQLServerDataSource dataSource = new SQLServerDataSource();
dataSource.setUser("sauser");
dataSource.setPassword("sauserpw");
dataSource.setServerName("localhost");
dataSource.setDatabaseName("Test");


@Repository
public class CustomerRepositoryImpl implements CustomerRepository {

    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    public CustomerRepositoryImpl(DatabaseConfig databaseConfig) {
        this.namedParameterJdbcTemplate = databaseConfig.namedParameterJdbcTemplate();

注意:没有错误,试图减少代码库并简化它

java sql-server spring-boot jdbctemplate
1个回答
0
投票

你为什么要尝试创建

DatabaseConfig
?我手头没有源代码,但是您当前的代码正在运行,您将获得一个由 autocobfiguration 创建的 jdbc-Template 注入(作为单例)。

自动配置的实现方式是,当满足某些条件时,它会退出,以便不干扰手动配置。

很有可能,通过自己创建 jdbctemplate,数据源配置会退出。

您可以通过在调试模式下启动 spring boot 来检查这一点。您可以在那里看到选择了哪些自动配置、省略了哪些以及原因。

如果您仍然想创建自己的jdbc模板,您可以像Spring Boot一样创建数据源。在这种情况下,我会查看相应的 Spring Boot 源代码。例如。数据库属性加载到

DatabaseProperties
bean 中...

© www.soinside.com 2019 - 2024. All rights reserved.