有时候,一个系统的功能,需要两个或两个以上的数据库,
在Spring Boot 中要如何配置? How to?
#primary primary.spring.datasource.jdbc-url=jdbc:mysql://localhost:3316/test1 primary.spring.datasource.username=root primary.spring.datasource.password=root primary.spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver #secondary secondary.spring.datasource.jdbc-url=jdbc:mysql://localhost:3316/test2 secondary.spring.datasource.username=root secondary.spring.datasource.password=root secondary.spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
新建一个类DataSourceConfig
@Configuration public class DataSourceConfig { @Bean(name = "primaryDataSource") @Qualifier("primaryDataSource") @Primary @ConfigurationProperties(prefix="primary.spring.datasource") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "secondaryDataSource") @Qualifier("secondaryDataSource") @ConfigurationProperties(prefix="secondary.spring.datasource") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "primaryJdbcTemplate") public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) { return new JdbcTemplate(dataSource); } @Bean(name = "secondaryJdbcTemplate") public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) { return new JdbcTemplate(dataSource); } }
之后在运用的时候,注意@Qualifier
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class ApplicationTests { @Autowired @Qualifier("primaryJdbcTemplate") protected JdbcTemplate jdbcTemplate1; @Autowired @Qualifier("secondaryJdbcTemplate") protected JdbcTemplate jdbcTemplate2; @Before public void setUp() { jdbcTemplate1.update("DELETE FROM USER "); jdbcTemplate2.update("DELETE FROM USER "); } @Test public void test() throws Exception { // 往第一个数据源中插入两条数据 jdbcTemplate1.update("insert into user(id,name,age) values(?, ?, ?)", 1, "aaa", 20); jdbcTemplate1.update("insert into user(id,name,age) values(?, ?, ?)", 2, "bbb", 30); }}
java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName.
修改application.xml中的数据库的url, 用spring.datasource.jdbc-url,而不是通常使用的spring.datasource.url。
之前用的如下截图,总是报错