首页 > 解决方案 > 使用 java 代码中的数据库属性在 Spring 中配置连接池

问题描述

我需要在 Web 应用程序中配置连接池。使用 common-dbcp 我写道:

@Configuration
public class SpringConfig {
    @Bean
    @Singleton
    public DataSource getDataSource() {
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        basicDataSource.setUrl("jdbc:mysql://localhost:3306/db?serverTimezone=UTC");
        basicDataSource.setUsername("name");
        basicDataSource.setPassword("password");
        basicDataSource.setInitialSize(5);
        basicDataSource.setMinIdle(3);
        basicDataSource.setMaxIdle(15);
        basicDataSource.setMaxWait(10000);
        basicDataSource.setMaxActive(100);
        return basicDataSource;
    }
}

我正在尝试使用 database.properties 文件对其进行配置。

    @Configuration
    @PropertySource("classpath:database.properties")
    public class SpringConfig {
        private @Value("${propertyName}") String propertyField;

        @Bean
        @Singleton
        public DataSource getDataSource() {
            BasicDataSource basicDataSource = new BasicDataSource();
            basicDataSource.setConnectionProperties(propertyField);
            return basicDataSource;
        }
    }

我创建了 database.properties 并将其放在目录src/main/resources中。内容如下:

driverClassName = "com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/db"
username="user"
password="password"

但它告诉我“财产未使用”。我做错了什么?

更新
解决方案是

@Configuration
@PropertySource("classpath:/database.properties")
public class SpringConfig {
    @Autowired
    Environment environment;

    @Bean
    @Singleton
    public DataSource getDataSource() {
            BasicDataSource basicDataSource = new BasicDataSource();
            basicDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
            basicDataSource.setUrl("jdbc:mysql://localhost:3306/dbname?serverTimezone=UTC");
            basicDataSource.setUsername(environment.getProperty("username"));
            basicDataSource.setPassword(environment.getProperty("password"));
            ..other actions is here
       }
}

重要提示:
您应该在进行其他设置之前setUserName()并按setPassword()以下顺序进行。

标签: javadatabasejdbcdatasourceconnection-pooling

解决方案


我假设此配置不适用于测试,因为测试需要不同的注释。您提到该文件位于资源文件夹中。你能确认它的 src/main/resources 是否存在吗?如此处详述您也不需要 @PropertySource 注释。您还可以尝试使用此处详述的 jvm 属性“--spring.config.location=classpath:/another-location.properties”作为示例。


推荐阅读