diff --git a/docs/zh/core/multi-datasource.md b/docs/zh/core/multi-datasource.md index 6a1845b3..feaf482a 100644 --- a/docs/zh/core/multi-datasource.md +++ b/docs/zh/core/multi-datasource.md @@ -198,5 +198,21 @@ HikariDataSource newDataSource = new HikariDataSource(); flexDataSource.addDataSource("newKey", newDataSource); ``` -> 需要注意的是:通过 FlexGlobalConfig 去获取 FlexDataSource 时,需等待应用完全启动成功后,才能正常获取 FlexDataSource, -> 否则将会得到 null 值。 \ No newline at end of file +**需要注意的是:** 通过 FlexGlobalConfig 去获取 FlexDataSource 时,需等待应用完全启动成功后,才能正常获取 FlexDataSource, +否则将会得到 null 值。 + +Spring 用户可以通过 `ApplicationListener` 去监听 `ContextRefreshedEvent` 事件,然后再去添加新的数据源,如下代码所示: + +```java +public class DataSourceInitListener implements ApplicationListener { + + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + FlexDataSource dataSource = (FlexDataSource) FlexGlobalConfig.getDefaultConfig() + .getConfiguration().getEnvironment().getDataSource(); + + dataSource.addDataSource("....", new DruidDataSource("...")); + } + +} +``` \ No newline at end of file diff --git a/mybatis-flex-test/mybatis-flex-spring-boot-test/src/main/java/com/mybatisflex/test/DataSourceInitListener.java b/mybatis-flex-test/mybatis-flex-spring-boot-test/src/main/java/com/mybatisflex/test/DataSourceInitListener.java new file mode 100644 index 00000000..276c872b --- /dev/null +++ b/mybatis-flex-test/mybatis-flex-spring-boot-test/src/main/java/com/mybatisflex/test/DataSourceInitListener.java @@ -0,0 +1,20 @@ +package com.mybatisflex.test; + +import com.mybatisflex.core.FlexGlobalConfig; +import com.mybatisflex.core.datasource.FlexDataSource; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.stereotype.Component; + +@Component +public class DataSourceInitListener implements ApplicationListener { + + @Override + public void onApplicationEvent(ContextRefreshedEvent event) { + FlexDataSource dataSource = (FlexDataSource) FlexGlobalConfig.getDefaultConfig() + .getConfiguration().getEnvironment().getDataSource(); + + System.out.println("onApplicationEvent>>>> datasource:" + dataSource); + } + +}