在Spring Boot中,我们经常需要连接多个数据库,并且使用JdbcTemplate来执行SQL操作。在Spring Boot 1.1.0版本之后,我们可以更加方便地配置和使用多个数据源。
多个DataSource的配置在Spring Boot中,我们可以通过在application.properties文件中配置多个DataSource来连接多个数据库。首先,我们需要为每个数据库配置一个数据源和一个JdbcTemplate。例如,我们想要连接两个数据库,分别是主数据库和日志数据库。首先,我们需要在application.properties文件中配置两个数据源的连接信息:# 主数据库配置spring.datasource.primary.url=jdbc:mysql://localhost:3306/mainspring.datasource.primary.username=rootspring.datasource.primary.password=123456# 日志数据库配置spring.datasource.log.url=jdbc:mysql://localhost:3306/logspring.datasource.log.username=rootspring.datasource.log.password=123456接下来,我们需要创建两个数据源和两个JdbcTemplate的bean。可以使用@Configuration注解来声明一个配置类,并使用@Bean注解来创建这些bean。例如:
java@Configurationpublic class DataSourceConfig { // 主数据源配置 @Bean @Primary @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } // 主JdbcTemplate配置 @Bean @Primary public JdbcTemplate primaryJdbcTemplate(DataSource primaryDataSource) { return new JdbcTemplate(primaryDataSource); } // 日志数据源配置 @Bean @ConfigurationProperties(prefix = "spring.datasource.log") public DataSource logDataSource() { return DataSourceBuilder.create().build(); } // 日志JdbcTemplate配置 @Bean public JdbcTemplate logJdbcTemplate(DataSource logDataSource) { return new JdbcTemplate(logDataSource); }}在上面的代码中,我们使用@ConfigurationProperties注解来将配置文件中的属性注入到DataSource的bean中。@Primary注解用于标识主数据源和主JdbcTemplate,而不标记的数据源和JdbcTemplate将被认为是次要的。使用多个DataSource和JdbcTemplate一旦我们配置好了多个DataSource和JdbcTemplate,我们就可以在代码中使用它们来执行SQL操作了。可以在需要使用的地方注入JdbcTemplate,并使用它来执行SQL语句。例如,我们可以创建一个UserService类来操作主数据库中的用户表,以及一个LogService类来操作日志数据库中的日志表。代码示例如下:java@Servicepublic class UserService { private final JdbcTemplate jdbcTemplate; @Autowired public UserService(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void addUser(String username, String password) { String sql = "INSERT INTO user (username, password) VALUES (?, ?)"; jdbcTemplate.update(sql, username, password); } // 其他操作方法...}@Servicepublic class LogService { private final JdbcTemplate jdbcTemplate; @Autowired public LogService(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void addLog(String message) { String sql = "INSERT INTO log (message) VALUES (?)"; jdbcTemplate.update(sql, message); } // 其他操作方法...}在上面的代码中,我们分别在UserService和LogService中注入了主JdbcTemplate和日志JdbcTemplate,并使用它们来执行相应的SQL操作。在Spring Boot中,通过配置多个DataSource和JdbcTemplate,我们可以很方便地连接和操作多个数据库。使用@ConfigurationProperties注解将配置文件中的属性注入到DataSource的bean中,使用@Primary注解标识主数据源和主JdbcTemplate。在代码中,可以通过注入JdbcTemplate来执行SQL操作。这样,我们就可以轻松地在一个应用程序中操作多个数据库了。