java - 使用 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()
以下顺序进行。
解决方案
我假设此配置不适用于测试,因为测试需要不同的注释。您提到该文件位于资源文件夹中。你能确认它的 src/main/resources 是否存在吗?如此处详述,您也不需要 @PropertySource 注释。您还可以尝试使用此处详述的 jvm 属性“--spring.config.location=classpath:/another-location.properties”作为示例。
推荐阅读
- arrays - 在 Invoke-AzureRmVMRunCommand 参数哈希表中传递数组不起作用
- datatable - 按数据查找 DataTable 单元格
- javascript - Angular 4中的路由更改时组件未正确呈现
- spring-boot - 微服务中的通用逻辑
- python - 使用 Databricks Job api 调用 databricks notebook 使用 AWS Lambda 函数运行-提交端点
- angular - 如何替换父组件内的组件
- java - 如何获取我的应用在 azure 中运行的虚拟机名称
- google-signin - Google 登录权限“查看并下载您的所有 Google 帐户电子邮件地址”
- angular - ngx-material-timepicker 不适用于 IE 和 Edge
- swift - 在 firebase 和 firebasecore 之间启动应用程序时不兼容