Spring Boot 2.x basic tutorial: multi-data source configuration of JdbcTemplate

In the previous tutorials in this series, we have introduced how to use the three most commonly used data access methods:

Below we will be divided into three articles to introduce the configuration instructions of how to use these three data access methods when we need multiple data sources.

Add the configuration of multiple data sources

First application.propertiesset up two database configurations that you want to link in the Spring Boot configuration file , such as this:

spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/test1
spring.datasource.primary.username=root
spring.datasource.primary.password=123456
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver

spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/test2
spring.datasource.secondary.username=root
spring.datasource.secondary.password=123456
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver

Description and note :

  1. When configuring multiple data sources, the difference from single data source is that spring.datasourceafter setting up a data source name primaryand secondarydistinguishing different data source configurations, this prefix will be used in subsequent initialization of data sources.
  2. Data source connection configuration 2.x and 1.x configuration items are different: 2.x use spring.datasource.secondary.jdbc-url, and 1.x version use spring.datasource.secondary.url. If this error occurs during configuration java.lang.IllegalArgumentException: jdbcUrl is required with driverClassName., then it is a problem with this configuration item.

Related reading: Spring Boot 1.x basic tutorial: multiple data source configuration

Initialize the data source and JdbcTemplate

After completing the configuration information for multiple data sources, create a configuration class to load the configuration information, initialize the data source, and initialize the JdbcTemplate used by each data source. You only need to add the following configuration class under your Spring Boot application to complete!

@Configuration
public class DataSourceConfiguration {
    
    

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
    
    
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
    
    
        return DataSourceBuilder.create().build();
    }

    @Bean
    public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
    
    
        return new JdbcTemplate(primaryDataSource);
    }

    @Bean
    public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
    
    
        return new JdbcTemplate(secondaryDataSource);
    }

}

Description and note :

  1. The first two Beans are the creation of data sources, and @ConfigurationPropertiesyou can know that these two data sources have loaded spring.datasource.primary.*and spring.datasource.secondary.*configuration respectively .
  2. @PrimaryThe annotation specifies the main data source, that is, when we do not specify which data source, this Bean will be used
  3. The latter two Beans correspond to each data source JdbcTemplate. You can see that JdbcTemplatewhen these two were created, the primaryDataSourcedata source and the secondaryDataSourcedata source were injected respectively

have a test

After completing the above, we can write a test class to try whether the above multiple data source configuration is correct, such as the following:

@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter37ApplicationTests {
    
    

    @Autowired
    protected JdbcTemplate primaryJdbcTemplate;

    @Autowired
    protected JdbcTemplate secondaryJdbcTemplate;

    @Before
    public void setUp() {
    
    
        primaryJdbcTemplate.update("DELETE  FROM  USER ");
        secondaryJdbcTemplate.update("DELETE  FROM  USER ");
    }

    @Test
    public void test() throws Exception {
    
    
        // 往第一个数据源中插入 2 条数据
        primaryJdbcTemplate.update("insert into user(name,age) values(?, ?)", "aaa", 20);
        primaryJdbcTemplate.update("insert into user(name,age) values(?, ?)", "bbb", 30);

        // 往第二个数据源中插入 1 条数据,若插入的是第一个数据源,则会主键冲突报错
        secondaryJdbcTemplate.update("insert into user(name,age) values(?, ?)", "ccc", 20);

        // 查一下第一个数据源中是否有 2 条数据,验证插入是否成功
        Assert.assertEquals("2", primaryJdbcTemplate.queryForObject("select count(1) from user", String.class));

        // 查一下第一个数据源中是否有 1 条数据,验证插入是否成功
        Assert.assertEquals("1", secondaryJdbcTemplate.queryForObject("select count(1) from user", String.class));
    }

}

Description and note :

  1. You may ask here, there are two JdbcTemplate, why not @Qualifierspecify? Incidentally, here is a little knowledge point. When we don't specify it, the name of the parameter will be used to find the Bean, and if it exists, it will be injected.
  2. When the two JdbcTemplates were created, we did not specify the names. How do they match? This is also a small knowledge point. When we create a Bean, the method name will be used as the name of the Bean by default, so here is the correspondence. Readers may wish to look back to see if the two names are the same?

Code example

For related examples in this article, you can view the chapter3-7directories in the following warehouse :

  • Github:https://github.com/dyc87112/SpringBoot-Learning/
  • Gitee:https://gitee.com/didispace/SpringBoot-Learning/

If you think this article is good, welcome Star support, your attention is my motivation for persistence!

This article was first published in: Spring Boot 2.x Basic Tutorial: Multi-data source configuration of JdbcTemplate, please indicate the source for reprinting. This series of thematic content can click free learning !

Guess you like

Origin blog.csdn.net/dyc87112/article/details/106891180