我需要在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()
。