|
@@ -0,0 +1,49 @@
|
|
|
|
+package com.qmth.boot.mybatis.service;
|
|
|
|
+
|
|
|
|
+import org.apache.commons.lang3.StringUtils;
|
|
|
|
+import org.slf4j.Logger;
|
|
|
|
+import org.slf4j.LoggerFactory;
|
|
|
|
+import org.springframework.aop.support.AopUtils;
|
|
|
|
+import org.springframework.context.ApplicationListener;
|
|
|
|
+import org.springframework.context.event.ContextRefreshedEvent;
|
|
|
|
+import org.springframework.jdbc.core.JdbcTemplate;
|
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
|
+
|
|
|
|
+import java.util.Map;
|
|
|
|
+
|
|
|
|
+@Component
|
|
|
|
+public class DatabaseInitializeService implements ApplicationListener<ContextRefreshedEvent> {
|
|
|
|
+
|
|
|
|
+ private static final Logger log = LoggerFactory.getLogger(DatabaseInitializeService.class);
|
|
|
|
+
|
|
|
|
+ private static final String SQL_SPLITE = ";";
|
|
|
|
+
|
|
|
|
+ private JdbcTemplate jdbcTemplate;
|
|
|
|
+
|
|
|
|
+ public DatabaseInitializeService(JdbcTemplate jdbcTemplate) {
|
|
|
|
+ this.jdbcTemplate = jdbcTemplate;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ @Override
|
|
|
|
+ public synchronized void onApplicationEvent(ContextRefreshedEvent event) {
|
|
|
|
+ if (event.getApplicationContext().getParent() == null) {
|
|
|
|
+ Map<String, SqlProvider> beans = event.getApplicationContext().getBeansOfType(SqlProvider.class);
|
|
|
|
+ for (SqlProvider provider : beans.values()) {
|
|
|
|
+ String beanName = AopUtils.getTargetClass(provider).getName();
|
|
|
|
+ String content = StringUtils.trimToNull(provider.get());
|
|
|
|
+ if (content == null) {
|
|
|
|
+ throw new RuntimeException("Blank content from SqlProvider: " + beanName);
|
|
|
|
+ }
|
|
|
|
+ String[] lines = StringUtils.split(content, SQL_SPLITE);
|
|
|
|
+ int count = 0;
|
|
|
|
+ for (String sql : lines) {
|
|
|
|
+ if (StringUtils.isNotBlank(sql)) {
|
|
|
|
+ jdbcTemplate.execute(sql);
|
|
|
|
+ count++;
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ log.info("Database initialize from SqlProvider: {}, execute count: {}", beanName, count);
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+ }
|
|
|
|
+}
|