File tree Expand file tree Collapse file tree
simple-common/src/main/java/top/cadecode/common/datasource
simple-web/src/main/resources Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package top .cadecode .common .datasource ;
2+
3+ import org .springframework .boot .SpringApplication ;
4+ import org .springframework .boot .env .EnvironmentPostProcessor ;
5+ import org .springframework .boot .env .YamlPropertySourceLoader ;
6+ import org .springframework .core .env .ConfigurableEnvironment ;
7+ import org .springframework .core .env .PropertySource ;
8+ import org .springframework .core .io .ClassPathResource ;
9+ import org .springframework .core .io .Resource ;
10+
11+ import java .io .IOException ;
12+
13+ /**
14+ * @author Li Jun
15+ * @date 2021/12/3
16+ * @description 将数据源配置文件加入到 Environment
17+ */
18+ public class DataSourceEnvironment implements EnvironmentPostProcessor {
19+
20+ private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader ();
21+
22+ @ Override
23+ public void postProcessEnvironment (ConfigurableEnvironment environment , SpringApplication application ) {
24+ Resource path = new ClassPathResource ("dataSource.yml" );
25+ PropertySource <?> propertySource = loadDataSourceYaml (path );
26+ environment .getPropertySources ().addLast (propertySource );
27+ }
28+
29+ // 加载 dataSource.yml
30+ private PropertySource <?> loadDataSourceYaml (Resource path ) {
31+ if (!path .exists ()) {
32+ throw new IllegalArgumentException ("数据源配置文件 " + path + " 不存在" );
33+ }
34+ try {
35+ return this .loader .load ("dataSource.yml" , path ).get (0 );
36+ } catch (IOException ex ) {
37+ throw new IllegalStateException ("加载 dataSource.yml 时出错,路径是 " + path , ex );
38+ }
39+ }
40+ }
Original file line number Diff line number Diff line change 1+ # 将数据源配置文件加入 Environment
2+ org.springframework.boot.env.EnvironmentPostProcessor=top.cadecode.common.datasource.DataSourceEnvironment
Original file line number Diff line number Diff line change 1+ # 配置数据源
2+ dataSource :
3+ db1 :
4+ # 指定 dataSource 种类
5+ type : com.zaxxer.hikari.HikariDataSource
6+ # 指定连接配置
7+ config :
8+ jdbc-url : jdbc:mysql://localhost:3306/demo?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
9+ driver-class-name : com.mysql.cj.jdbc.Driver
10+ username : root
11+ password : xxxx
12+ db2 :
13+ type : com.zaxxer.hikari.HikariDataSource
14+ config :
15+ jdbc-url : jdbc:mysql://localhost:3306/demo_cluster?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
16+ driver-class-name : com.mysql.cj.jdbc.Driver
17+ username : root
18+ password : xxxx
19+ # 默认数据源
20+ default : db2
You can’t perform that action at this time.
0 commit comments