Spring应用schema.sql未执行且类路径不存在问题求助
schema.sql in Spring Boot Dev Environment Let's work through your issue step by step—you've got schema.sql in your Resources folder and a working application-dev.yml, but the SQL isn't running on startup, and manual path configs throw "resource doesn't exist" errors. Here's how to get it working:
1. Double-Check Your File Location & Classpath
First, make sure schema.sql is in the right Resources directory:
- For Maven projects:
src/main/resources/schema.sql - For Gradle projects:
src/main/resources/schema.sql
After building your project, verify the file ends up in your compiled classpath:
- Maven: Check
target/classes/schema.sql - Gradle: Check
build/resources/main/schema.sql
If it's missing, fix your build config to ensure resources are copied correctly during compilation.
2. Enable SQL Initialization (Critical for Non-Embedded Databases)
Spring Boot auto-runs schema.sql only for embedded databases (like H2) by default. If you're using a full database (MySQL, PostgreSQL, etc.), you need to explicitly enable initialization in your application-dev.yml:
For Spring Boot 2.5+ (Recommended)
Use the updated spring.sql.init properties:
spring: sql: init: mode: always # Runs schema.sql EVERY time the app starts (safe for dev only!) schema-locations: classpath:schema.sql # No leading slash—classpath root maps to resources/
For Spring Boot <2.5
Use the older spring.datasource properties:
spring: datasource: initialization-mode: always schema: classpath:schema.sql
3. Fix the Resource Path Issue
The error [\schema.sql] resource doesn't exist happens because you added a leading slash. Classpath resources are referenced without the leading /—classpath:schema.sql points directly to your src/main/resources/schema.sql file.
4. Confirm Your Dev Profile Is Active
Even though application-dev.yml is readable, double-check that the dev profile is actually active when you start the app:
- Add a startup argument:
--spring.profiles.active=dev - Or set it in your root
application.yml:spring: profiles: active: dev
5. Check for Overriding Configs
Make sure no other properties are disabling initialization. Look for these in your configs and remove them if present:
spring.sql.init.enabled=false(Spring Boot 2.5+)spring.datasource.initialize=false(Spring Boot <2.5)
Once you apply these changes, restart your app—your schema.sql should run on startup, and the customers table will be created and populated automatically.
内容的提问来源于stack exchange,提问作者ScaVenGerS

