使用 java 代码中的数据库属性在 Spring 中配置连接池

Configuring Connection Pool in Spring using database properties in java code

我需要在网络应用程序中配置连接池。我使用 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()

我假设此配置不适用于测试,因为测试需要不同的注释。您提到该文件位于资源文件夹中。你能确认它是 src/main/resources 吗?详细如here you don't need the @PropertySource annotation too. You also try using the jvm property "--spring.config.location=classpath:/another-location.properties" as detailed here举例