java - 在 Spring 应用程序的类路径中找不到 Schema.sql
问题描述
schema.sql
我的资源文件夹中有一个文件以及application-dev.yml
应用程序设置,它看起来如下:
-- Drop the tables
DROP TABLE IF EXISTS customers;
-- Create tables
CREATE TABLE customers (
id SERIAL,
first_name VARCHAR(255),
last_name VARCHAR(255)
);
-- Populate data
INSERT INTO customers(first_name, last_name) VALUES ('Jane', 'Doe');
INSERT INTO customers(first_name, last_name) VALUES ('Josh', 'Gruber');
INSERT INTO customers(first_name, last_name) VALUES ('Hans', 'Gruber');
INSERT INTO customers(first_name, last_name) VALUES ('John', 'Doe');
但是在应用程序启动时它并没有被执行,因为当我尝试在程序中查询它时,我收到一条错误消息,说“客户”不存在。我试过手动设置属性spring.datasource.schema: 'schema.sql'
,但我得到一个错误提示[\schema.sql] resource doesn't exist on the classpath
。我知道它确实是因为application-dev.yml
必须在类路径上才能读取属性(这会被读取并导致找不到资源的错误)。
我是在搞乱类路径还是我错过了一些可以指定每次应用程序在开发环境中运行时如何初始化我的数据库的属性?
解决方案
作为一种解决方案,我检查了我的配置文件 ( spring.profiles.active
) 是否包含dev
,如果包含,则执行资源schema.sql
。令人惊讶的是,在运行时发现ResourceDatabasePopulator
没有错误。以下是我用作解决方案的代码:
@Autowired
Environment env;
// If the environment is dev, then run schema.sql to reinitialize the schema and repopulate test data
if(env.getActiveProfiles()[0].equalsIgnoreCase("dev")) {
Resource resource = new ClassPathResource("schema.sql");
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(resource);
databasePopulator.execute(dataSource);
}
推荐阅读
- python - 列出两个数据框列之间的工作日
- google-apps-script - 我可以使用 Apps 脚本设置/更改所有者 Google 日历活动吗?
- c++ - 字符串在操作它的过程中被切断
- python - 哨兵值排序和反向排序
- python - 30 类的 LSTM,严重过拟合,不能超过 76% 的测试准确率
- ssis - 完成后使SSIS foreach循环重新扫描文件夹
- python - 在多处理池进程中运行代码
- mysql - root 用户无权访问 RDS MYSql 实例
- scala - 在 SBT 项目中运行标记测试
- python - 带有graphql的Aiohttp:字符串不能代表值