springboot 多数据源测试类
时间: 2024-03-06 08:45:23 浏览: 21
在Spring Boot中,实现多数据源的方式有很多种,其中一种常用的方式是通过配置多个数据源,并使用`@Primary`和`@Qualifier`注解来指定默认数据源和其他数据源。
下面是一个简单的示例代码,展示了如何在Spring Boot中实现多数据源的测试类:
```java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
@SpringBootTest
public class MultiDataSourceTest {
@Autowired
private JdbcTemplate primaryJdbcTemplate;
@Autowired
@Qualifier("secondaryJdbcTemplate")
private JdbcTemplate secondaryJdbcTemplate;
@Test
public void testMultiDataSource() {
// 使用primaryJdbcTemplate操作默认数据源
primaryJdbcTemplate.execute("INSERT INTO table1(id, name) VALUES (1, 'Data from primary data source')");
// 使用secondaryJdbcTemplate操作其他数据源
secondaryJdbcTemplate.execute("INSERT INTO table2(id, name) VALUES (2, 'Data from secondary data source')");
}
}
```
在上述代码中,我们通过`@Autowired`注解注入了两个`JdbcTemplate`对象,分别对应默认数据源和其他数据源。通过调用`execute`方法,我们可以执行SQL语句来操作相应的数据源。