application.yml文件中配置多个数据源报错找不到数据源
时间: 2023-08-06 16:03:48 浏览: 225
出现这种情况一般是因为在多数据源配置时,没有正确指定默认数据源。可以尝试在application.yml中添加以下代码:
```
spring:
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/defaultdb?useSSL=false
username: root
password: root
hikari:
minimum-idle: 10
maximum-pool-size: 100
auto-commit: true
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
connection-test-query: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
filters: stat,wall,log4j
default:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/my_db1?useSSL=false
username: root
password: root
hikari:
minimum-idle: 10
maximum-pool-size: 100
auto-commit: true
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
connection-test-query: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
filters: stat,wall,log4j
db2:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/my_db2?useSSL=false
username: root
password: root
hikari:
minimum-idle: 10
maximum-pool-size: 100
auto-commit: true
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
connection-test-query: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
filters: stat,wall,log4j
```
其中,`default`表示默认数据源,`db2`为第二个数据源。需要注意的是,多数据源配置时,需要在使用的地方指定具体的数据源。例如,在DAO层中,可以使用`@Qualifier`注解指定使用的数据源名称,如:
```
@Repository
@Qualifier("db2")
public class UserDaoImpl implements UserDao {
@Autowired
@Qualifier("db2")
private JdbcTemplate jdbcTemplate;
//...
}
```
阅读全文