springboot+DruidDataSource+shardingsphere数据库配置不放yml放配置类
时间: 2023-08-21 08:05:21 浏览: 158
您可以通过创建一个配置类来配置springboot+DruidDataSource+shardingsphere的数据库配置,而不是将配置信息放在yml文件中。以下是一个示例配置类的代码:
```java
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean
public DataSourceProxy dataSourceProxy(DataSource dataSource) {
return new DataSourceProxy(dataSource);
}
@Bean
public DataSourceRule dataSourceRule(DataSourceProxy dataSourceProxy) {
DataSourceRule dataSourceRule = new DataSourceRule(dataSourceProxy);
// 配置分库分表规则
// dataSourceRule.addDataSourceRule(...)
// dataSourceRule.addTableRule(...)
return dataSourceRule;
}
@Bean
public ShardingRule shardingRule(DataSourceRule dataSourceRule) {
ShardingRule shardingRule = ShardingRule.builder()
.dataSourceRule(dataSourceRule)
// 配置分片规则
// shardingRule.getTableRuleConfigs().add(...)
.build();
return shardingRule;
}
@Bean
public DataSource dataSource(ShardingRule shardingRule) throws SQLException {
return ShardingDataSourceFactory.createDataSource(shardingRule);
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
// 配置其他属性
// sessionFactory.setMapperLocations(...)
return sessionFactory.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
```
您可以根据自己的需求在配置类中添加适当的配置,比如配置数据源、分库分表规则、分片规则等。这样,您就可以将数据库配置信息集中在一个配置类中,而不是放在yml文件中。
#### 引用[.reference_title]
- *1* *2* [springboot+druid连接池+mybatisplus+shardingsphere5.0alpha实现分库分表实战案例](https://blog.csdn.net/qq_40726812/article/details/120594172)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [Springboot+mybatis+shardingsphere 分库分表](https://blog.csdn.net/l_ian/article/details/120547449)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文