这篇文章将为大家详细讲解有关如何在Spring中执行sql脚本文件,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

创新互联公司一直在为企业提供服务,多年的磨炼,使我们在创意设计,成都全网营销到技术研发拥有了开发经验。我们擅长倾听企业需求,挖掘用户对产品需求服务价值,为企业制作有用的创意设计体验。核心团队拥有超过10多年以上行业经验,涵盖创意,策化,开发等专业领域,公司涉及领域有基础互联网服务服务器托管、成都APP应用开发、手机移动建站、网页设计、网络整合营销。
解决方法:
//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 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 getScripts(String propertyName, List resources,
String fallback) {
if (resources != null) {
return getResources(propertyName, resources, true);
}
String platform = this.properties.getPlatform();
List fallbackResources = new ArrayList();
fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");
fallbackResources.add("classpath*:" + fallback + ".sql");
return getResources(propertyName, fallbackResources, false);
} 关于如何在Spring中执行sql脚本文件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。