Spring 数据初始化
以前用xml,在容器启动时初始化一些数据,配置如下:
<beans profile="init">
<context:property-placeholder location="classpath:config-global.properties,classpath:config-env-init.properties"
file-encoding="UTF-8" />
<jdbc:initialize-database data-source="dataSource" enabled="true">
<jdbc:script execution="INIT" encoding="utf-8" location="classpath:sql/prod-data.sql" />
<jdbc:script execution="INIT" encoding="utf-8" location="classpath:sql/dev-data.sql" />
</jdbc:initialize-database>
</beans>
现在用SpringBoot,想实现加载sql脚本初始化数据的功能,查看spring-jdbc包发现org.springframework.jdbc.datasource.init,查看里面的类感觉可以用。
代码如下:
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
@Configuration
public class JdbcScriptTest extends SCMSpringBootTest {
@Autowired
private DataSource dataSource;
@Bean
public InitializingBean init() {
ClassPathResource recordsSys = new ClassPathResource("scm-records-sys.sql");
DataSourceInitializer dsi = new DataSourceInitializer();
dsi.setDataSource(dataSource);
dsi.setDatabasePopulator(new ResourceDatabasePopulator(true, true, "utf-8", recordsSys));
dsi.setEnabled(true);
return dsi;
}
@Test
public void test() {
System.out.println("successful");
}
}
在需要初始化数据的时候,执行这个junit即可,DataSourceInitializer 还有一个setDatabaseCleaner方法。
父类代码:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SCMSpringBootTest extends AbstractJUnit4SpringContextTests {
@Test
public void test() {
int beanDefinitionCount = applicationContext.getBeanDefinitionCount();
System.out.printf("共有%d个bean定义\n", beanDefinitionCount);
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String string : beanDefinitionNames) {
System.out.println(string);
}
}
}