提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.framework.test.config; |
H |
2 |
|
|
3 |
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; |
|
4 |
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; |
|
5 |
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate; |
|
6 |
import org.springframework.boot.autoconfigure.sql.init.SqlInitializationProperties; |
|
7 |
import org.springframework.boot.context.properties.EnableConfigurationProperties; |
|
8 |
import org.springframework.boot.jdbc.init.DataSourceScriptDatabaseInitializer; |
|
9 |
import org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer; |
|
10 |
import org.springframework.boot.sql.init.DatabaseInitializationSettings; |
|
11 |
import org.springframework.context.annotation.Bean; |
|
12 |
import org.springframework.context.annotation.Configuration; |
|
13 |
import org.springframework.context.annotation.Lazy; |
|
14 |
|
|
15 |
import javax.sql.DataSource; |
|
16 |
|
|
17 |
/** |
|
18 |
* SQL 初始化的测试 Configuration |
|
19 |
* |
|
20 |
* 为什么不使用 org.springframework.boot.autoconfigure.sql.init.DataSourceInitializationConfiguration 呢? |
|
21 |
* 因为我们在单元测试会使用 spring.main.lazy-initialization 为 true,开启延迟加载。此时,会导致 DataSourceInitializationConfiguration 初始化 |
|
22 |
* 不过呢,当前类的实现代码,基本是复制 DataSourceInitializationConfiguration 的哈! |
|
23 |
* |
|
24 |
* @author iailab |
|
25 |
*/ |
|
26 |
@Configuration(proxyBeanMethods = false) |
|
27 |
@ConditionalOnMissingBean(AbstractScriptDatabaseInitializer.class) |
|
28 |
@ConditionalOnSingleCandidate(DataSource.class) |
|
29 |
@ConditionalOnClass(name = "org.springframework.jdbc.datasource.init.DatabasePopulator") |
|
30 |
@Lazy(value = false) // 禁止延迟加载 |
|
31 |
@EnableConfigurationProperties(SqlInitializationProperties.class) |
|
32 |
public class SqlInitializationTestConfiguration { |
|
33 |
|
|
34 |
@Bean |
|
35 |
public DataSourceScriptDatabaseInitializer dataSourceScriptDatabaseInitializer(DataSource dataSource, |
|
36 |
SqlInitializationProperties initializationProperties) { |
|
37 |
DatabaseInitializationSettings settings = createFrom(initializationProperties); |
|
38 |
return new DataSourceScriptDatabaseInitializer(dataSource, settings); |
|
39 |
} |
|
40 |
|
|
41 |
static DatabaseInitializationSettings createFrom(SqlInitializationProperties properties) { |
|
42 |
DatabaseInitializationSettings settings = new DatabaseInitializationSettings(); |
|
43 |
settings.setSchemaLocations(properties.getSchemaLocations()); |
|
44 |
settings.setDataLocations(properties.getDataLocations()); |
|
45 |
settings.setContinueOnError(properties.isContinueOnError()); |
|
46 |
settings.setSeparator(properties.getSeparator()); |
|
47 |
settings.setEncoding(properties.getEncoding()); |
|
48 |
settings.setMode(properties.getMode()); |
|
49 |
return settings; |
|
50 |
} |
|
51 |
|
|
52 |
} |