Spring Boot 多数据源配置示例 - 使用JdbcTemplate访问数据库
下面是一个简单的示例,使用 Spring Boot 配置多个数据源:
首先,在 application.properties 文件中配置数据源:
# 数据源1
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 数据源2
spring.second-datasource.url=jdbc:mysql://localhost:3306/db2
spring.second-datasource.username=root
spring.second-datasource.password=123456
spring.second-datasource.driver-class-name=com.mysql.jdbc.Driver
然后,创建两个 DataSource 对象并将它们注入到 Spring 容器中:
@Configuration
public class DataSourceConfig {
@Bean(name = 'dataSource')
@Primary
@ConfigurationProperties(prefix = 'spring.datasource')
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = 'secondDataSource')
@ConfigurationProperties(prefix = 'spring.second-datasource')
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
}
在上面的代码中,@Primary 注解表示将 dataSource 对象作为默认的数据源。
接下来,创建 JdbcTemplate 对象,使用注入的数据源:
@Configuration
public class JdbcTemplateConfig {
@Autowired
@Qualifier('dataSource')
private DataSource dataSource;
@Autowired
@Qualifier('secondDataSource')
private DataSource secondDataSource;
@Bean(name = 'jdbcTemplate')
public JdbcTemplate jdbcTemplate() {
return new JdbcTemplate(dataSource);
}
@Bean(name = 'secondJdbcTemplate')
public JdbcTemplate secondJdbcTemplate() {
return new JdbcTemplate(secondDataSource);
}
}
最后,在需要使用数据源的地方注入 JdbcTemplate 对象,并使用它来访问数据库:
@Service
public class UserService {
@Autowired
@Qualifier('jdbcTemplate')
private JdbcTemplate jdbcTemplate;
@Autowired
@Qualifier('secondJdbcTemplate')
private JdbcTemplate secondJdbcTemplate;
public void addUser(User user) {
jdbcTemplate.update('INSERT INTO user(name, age) VALUES(?, ?)', user.getName(), user.getAge());
}
public void addSecondUser(User user) {
secondJdbcTemplate.update('INSERT INTO user(name, age) VALUES(?, ?)', user.getName(), user.getAge());
}
}
上面的示例展示了如何在 Spring Boot 中配置多个数据源,并使用 JdbcTemplate 访问它们。
原文地址: https://www.cveoy.top/t/topic/nGoI 著作权归作者所有。请勿转载和采集!