您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關如何在Spring中執行sql腳本文件,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
解決方法:
//Schema 處理器 @Component public class SchemaHandler { private final String SCHEMA_SQL = "classpath:schema.sql"; @Autowired private DataSource datasource; @Autowired private SpringContextGetter springContextGetter; public void execute() throws Exception { Resource resource = springContextGetter.getApplicationContext().getResource(SCHEMA_SQL); ScriptUtils.executeSqlScript(datasource.getConnection(), resource); } } // 獲取 ApplicationContext @Component public class SpringContextGetter implements ApplicationContextAware { private ApplicationContext applicationContext; public ApplicationContext getApplicationContext() { return applicationContext; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
備注:
關于為何 Spring 會去執行 classpath:schema.sql,可以參考源碼
org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer#runSchemaScripts
private void runSchemaScripts() { List<Resource> scripts = getScripts("spring.datasource.schema", this.properties.getSchema(), "schema"); if (!scripts.isEmpty()) { String username = this.properties.getSchemaUsername(); String password = this.properties.getSchemaPassword(); runScripts(scripts, username, password); try { this.applicationContext .publishEvent(new DataSourceInitializedEvent(this.dataSource)); // The listener might not be registered yet, so don't rely on it. if (!this.initialized) { runDataScripts(); this.initialized = true; } } catch (IllegalStateException ex) { logger.warn("Could not send event to complete DataSource initialization (" + ex.getMessage() + ")"); } } } /** * 默認拿 classpath*:schema-all.sql 和 classpath*:schema.sql */ private List<Resource> getScripts(String propertyName, List<String> resources, String fallback) { if (resources != null) { return getResources(propertyName, resources, true); } String platform = this.properties.getPlatform(); List<String> fallbackResources = new ArrayList<String>(); fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql"); fallbackResources.add("classpath*:" + fallback + ".sql"); return getResources(propertyName, fallbackResources, false); }
關于如何在Spring中執行sql腳本文件就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。