1.代碼
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Map;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.origin.OriginTrackedValue;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
public class ConfigureListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
// 獲取spring Environment
MutablePropertySources propertySources = event.getEnvironment().getPropertySources();
// 配置放在了application-pro或者是application-dev 中 賦值複製需要在其中賦值
for (PropertySource<?> propertySource : propertySources) {
boolean applicationConfig = propertySource.getName().contains("application-");
if (!applicationConfig) {
continue;
}
// 獲取上文的application集合中獲取數據庫連接
Map<String, OriginTrackedValue> dataBaseSource =
(Map<String, OriginTrackedValue>)propertySource.getSource();
String driverClass = String.valueOf(dataBaseSource.get("spring.datasource.driver-class-name").getValue());
String url = String.valueOf(dataBaseSource.get("spring.datasource.url").getValue());
String user = String.valueOf(dataBaseSource.get("spring.datasource.username").getValue());
String password = String.valueOf(dataBaseSource.get("spring.datasource.password").getValue());
// 因爲在spring初始化之前 所有不能使用註解 所以需要jdbc直接連接數據庫 首先建立驅動
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, password);
// 1、獲取連接對象
// 2、創建statement類對象,用來執行SQL語句!!
st = conn.createStatement();
// 3、創建sql查詢語句
String sql = "select * from SYS_CONFIGURE";
// 4、執行sql語句並且換回一個查詢的結果集
rs = st.executeQuery(sql);
while (rs.next()) {
// 獲取數據庫中的數據
String item = rs.getString("ITEM");
String itemValue = rs.getString("ITEM_VALUE");
// 通過數據庫中的配置 修改application集合中數據
Map<String, OriginTrackedValue> source =
(Map<String, OriginTrackedValue>)propertySource.getSource();
OriginTrackedValue originTrackedValue = source.get(item);
OriginTrackedValue newOriginTrackedValue =
OriginTrackedValue.of(itemValue, originTrackedValue.getOrigin());
source.put(item, newOriginTrackedValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(TestApplication.class);
app.addListeners(new ConfigureListener());
app.run(args);
}
}
2.簡介
在spring boot初始化時 會讀取application 放在MutablePropertySources 中 我們會讀取配置MutablePropertySources 然後查詢數據庫 根據key查詢之後 重新覆蓋(因爲以上操作時 bean factory還沒有初始化 所以用jdbc)
而以上攔截器會在讀取application後立刻執行 不會馬後炮(當spring boot初始化之後在更改MutablePropertySources )
獲取MutablePropertySources
MutablePropertySources propertySources = event.getEnvironment().getPropertySources();