本篇解決 spring 執行sql腳本(文件)的問題。
場景描述可以不看。
場景描述:
我在運行單測的時候,也就是 spring 工程啟動的時候,spring 會去執行 classpath:schema.sql(后面會解釋),我想利用這一點,解決一個問題:
一次運行多個測試文件,每個文件先后獨立運行,而上一個文件創建的數據,會對下一個文件運行時造成影響,所以我要在每個文件執行完成之后,重置數據庫,不單單是把數據刪掉,而 schema.sql 里面有 drop table 和create table。
解決方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
//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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
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 ); } |
參考:https://github.com/spring-projects/spring-boot/issues/9048
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000018344940