2.13.4 - [lex.string] - 【词法.字符串】

博客围绕词法中的字符串展开,但内容仅包含版权声明,未提及信息技术相关关键信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

请不要转载本文;请不要以任何形式重新出版,发布本文;请在下载本文 24 小时内将其删除;禁止将本文用于商业目的。

2 Lexical conventions [lex]

2.13 Literals [lex.literal]
2.13.4 String literals [lex.string]

 

2 词法约定 【词法】

2.13 文字量 【词法.文字量】
2.13.4 字符串文字量 【词法.字符串】

 

    string-literal:
        "s-char-sequenceopt"
        L"s-char-sequenceopt"

    s-char-sequence:
        s-char
        s-char-sequence s-char

    s-char:
        any member of the source character set except
            the double-quote ", backslash /, or new-line character
        escape-sequence
        universal-character-name

 

    字符串-文字量:
        "s-字符-序列opt"
        L"s-字符-序列opt"

    s-字符-序列:
        s-字符
        s-字符-序列 s-字符

    s-字符:
        源字符集中的任何成员,除了
            双引号 ",反斜杠 /,或换行字符
        转义-序列
        统一字符名称

 

A string literal is a sequence of characters (as defined in 2.13.2) surrounded by double quotes, optionally beginning with the letter L, as in "..." or L"...". A string literal that does not begin with L is an ordinary string literal, also referred to as a narrow string literal. An ordinary string literal has type "array of n const char" and static storage duration (3.7), where n is the size of the string as defined below, and is initialized with the given characters. A string literal that begins with L, such as L"asdf", is a wide string literal. A wide string literal has type "array of n const wchar_t" and has static storage duration, where n is the size of the string as defined below, and is initialized with the given characters.

 

字符串文字量是由双引号包围的,可能由一个字母 L 开始的字符序列(2.13.2 中定义)组成,比如 "..."L"..."。不是由 L 开始的字符串文字量是普通字符串文字量,也被称为窄字符串文字量。普通字符串文字量具有类型“nconst char 的数组”和静态存储类型(3.7),其中 n 表示如下定义的字符串长度,并由给定的字符初始化。由 L 开始的字符串,如 L"asdf",是宽字符串文字量。宽字符串文字量具有类型“n const wchar_t 的数组”和静态存储类型,其中 n 表示如下定义的字符串长度,并由给定的字符初始化。

 

Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined. The effect of attempting to modify a string literal is undefined.

 

是否保持所有字符串文字量独立(就是说,被不重叠的存储到对象中)是由编译器定义的。尝试修改一个字符串文字量的效果是未定义的。

 

In translation phase 6 (2.1), adjacent narrow string literals are concatenated and adjacent wide string literals are concatenated. If a narrow string literal token is adjacent to a wide string literal token, the behavior is undefined. Characters in concatenated strings are kept distinct. [Example:

    "/xA" "B"

contains the two characters '/xA' and 'B' after concatenation (and not the single hexadecimal character '/xAB'). ]

 

在翻译第 6 阶段(2.1),相邻的窄字符串文字量被连接,相邻的宽字符串文字量被连接。如果窄字符串文字量标记与宽字符串文字量标记相邻,其行为是未定义的。被连接的字符串中的字符是独立存在的。【例:

    "/xA" "B"

在连接后将包含两个字符 '/xA' 和 'B'(而不是单个十六进制字符 '/xAB')。】

 

After any necessary concatenation, in translation phase 7 (2.1), '/0' is appended to every string literal so that programs that scan a string can find its end.

 

翻译第 7 阶段(2.1)中,在必要的连接之后,'/0' 被添加到每个字符串文字量之后,使得扫描字符串的程序可以找到它的结尾。

 

Escape sequences and universal-character-names in string literals have the same meaning as in character literals (2.13.2), except that the single quote ' is representable either by itself or by the escape sequence /', and the double quote " shall be preceded by a /. In a narrow string literal, a universal-character-name may map to more than one char element due to multibyte encoding. The size of a wide string literal is the total number of escape sequences, universal-character-names, and other characters, plus one for the terminating L'/0'. The size of a narrow string literal is the total number of escape sequences and other characters, plus at least one for the multibyte encoding of each universal-character-name, plus one for the terminating '/0'.

 

在字符串文字量中的转义序列和统一字符名称的意义与其在字符文字量(2.13.2)中相同,除了单引号 ' 能够代表自己,或被转义序列 /' 代表,并且双引号 " 必须由一个 / 开始。在窄字符串文字量中,统一字符名称可能被按照多字节编码映射到不只一个 char 元素。宽字符串文字量的长度是转义序列,统一字符名称,以及其他字符,加上一个结尾字符 L'/0' 的总数。窄字符串文字量的长度是转义序列以及其他字符,加上每个统一字符名称的多字节编码的至少一个字节数,再加上一个结尾字符 '/0'

 

PREV [lex.fcon] | NEXT [lex.bool]上一页 【词法.浮点常量】 | 下一页 【词法.布尔常量】
C:\Users\Administrator\.jdks\ms-17.0.15\bin\java.exe -XX:TieredStopAtLevel=1 -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-Dmanagement.endpoints.jmx.exposure.include=*" "-javaagent:C:\Users\Administrator\AppData\Local\Programs\IntelliJ IDEA Ultimate 2025.1.3\lib\idea_rt.jar=63069" -Dfile.encoding=UTF-8 -classpath C:\Users\Administrator\IdeaProjects\demo1\target\classes;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-starter-jdbc\2.6.13\spring-boot-starter-jdbc-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-starter\2.6.13\spring-boot-starter-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot\2.6.13\spring-boot-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-autoconfigure\2.6.13\spring-boot-autoconfigure-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-starter-logging\2.6.13\spring-boot-starter-logging-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\ch\qos\logback\logback-classic\1.2.11\logback-classic-1.2.11.jar;D:\apache-maven-3.9.10\maven-repository\ch\qos\logback\logback-core\1.2.11\logback-core-1.2.11.jar;D:\apache-maven-3.9.10\maven-repository\org\apache\logging\log4j\log4j-to-slf4j\2.17.2\log4j-to-slf4j-2.17.2.jar;D:\apache-maven-3.9.10\maven-repository\org\apache\logging\log4j\log4j-api\2.17.2\log4j-api-2.17.2.jar;D:\apache-maven-3.9.10\maven-repository\org\slf4j\jul-to-slf4j\1.7.36\jul-to-slf4j-1.7.36.jar;D:\apache-maven-3.9.10\maven-repository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;D:\apache-maven-3.9.10\maven-repository\org\yaml\snakeyaml\1.29\snakeyaml-1.29.jar;D:\apache-maven-3.9.10\maven-repository\com\zaxxer\HikariCP\4.0.3\HikariCP-4.0.3.jar;D:\apache-maven-3.9.10\maven-repository\org\slf4j\slf4j-api\1.7.36\slf4j-api-1.7.36.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-jdbc\5.3.23\spring-jdbc-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-beans\5.3.23\spring-beans-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-tx\5.3.23\spring-tx-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-starter-web\2.6.13\spring-boot-starter-web-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-starter-json\2.6.13\spring-boot-starter-json-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\com\fasterxml\jackson\core\jackson-databind\2.13.4.2\jackson-databind-2.13.4.2.jar;D:\apache-maven-3.9.10\maven-repository\com\fasterxml\jackson\core\jackson-annotations\2.13.4\jackson-annotations-2.13.4.jar;D:\apache-maven-3.9.10\maven-repository\com\fasterxml\jackson\core\jackson-core\2.13.4\jackson-core-2.13.4.jar;D:\apache-maven-3.9.10\maven-repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.13.4\jackson-datatype-jdk8-2.13.4.jar;D:\apache-maven-3.9.10\maven-repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.13.4\jackson-datatype-jsr310-2.13.4.jar;D:\apache-maven-3.9.10\maven-repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.13.4\jackson-module-parameter-names-2.13.4.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\boot\spring-boot-starter-tomcat\2.6.13\spring-boot-starter-tomcat-2.6.13.jar;D:\apache-maven-3.9.10\maven-repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.68\tomcat-embed-core-9.0.68.jar;D:\apache-maven-3.9.10\maven-repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.68\tomcat-embed-el-9.0.68.jar;D:\apache-maven-3.9.10\maven-repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.68\tomcat-embed-websocket-9.0.68.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-web\5.3.23\spring-web-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-webmvc\5.3.23\spring-webmvc-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-aop\5.3.23\spring-aop-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-context\5.3.23\spring-context-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-expression\5.3.23\spring-expression-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\mybatis\spring\boot\mybatis-spring-boot-starter\2.2.2\mybatis-spring-boot-starter-2.2.2.jar;D:\apache-maven-3.9.10\maven-repository\org\mybatis\spring\boot\mybatis-spring-boot-autoconfigure\2.2.2\mybatis-spring-boot-autoconfigure-2.2.2.jar;D:\apache-maven-3.9.10\maven-repository\org\mybatis\mybatis\3.5.9\mybatis-3.5.9.jar;D:\apache-maven-3.9.10\maven-repository\org\mybatis\mybatis-spring\2.0.7\mybatis-spring-2.0.7.jar;D:\apache-maven-3.9.10\maven-repository\com\h2database\h2\1.4.200\h2-1.4.200.jar;D:\apache-maven-3.9.10\maven-repository\com\mysql\mysql-connector-j\8.0.31\mysql-connector-j-8.0.31.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-core\5.3.23\spring-core-5.3.23.jar;D:\apache-maven-3.9.10\maven-repository\org\springframework\spring-jcl\5.3.23\spring-jcl-5.3.23.jar com.example.demo.Demo1Application . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.6.13) 2025-07-11 15:49:04.751 INFO 11328 --- [ main] com.example.demo.Demo1Application : Starting Demo1Application using Java 17.0.15 on 闫晓强 with PID 11328 (C:\Users\Administrator\IdeaProjects\demo1\target\classes started by Administrator in C:\Users\Administrator\IdeaProjects\demo1) 2025-07-11 15:49:04.753 INFO 11328 --- [ main] com.example.demo.Demo1Application : No active profile set, falling back to 1 default profile: "default" 2025-07-11 15:49:05.202 WARN 11328 --- [ main] o.m.s.mapper.ClassPathMapperScanner : No MyBatis mapper was found in '[com.example.demo]' package. Please check your configuration. 2025-07-11 15:49:05.483 INFO 11328 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2025-07-11 15:49:05.490 INFO 11328 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2025-07-11 15:49:05.490 INFO 11328 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.68] 2025-07-11 15:49:05.561 INFO 11328 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2025-07-11 15:49:05.561 INFO 11328 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 772 ms 2025-07-11 15:49:05.583 INFO 11328 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 2025-07-11 15:49:05.701 INFO 11328 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 2025-07-11 15:49:05.707 INFO 11328 --- [ main] o.s.b.a.h2.H2ConsoleAutoConfiguration : H2 console available at '/h2-console'. Database available at 'jdbc:mysql://localhost:3306/mysqlservicedbone?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8' 2025-07-11 15:49:05.860 INFO 11328 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html] 2025-07-11 15:49:05.967 WARN 11328 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.UncategorizedScriptException: Failed to execute database script from resource [class path resource [schema.sql]]; nested exception is java.lang.IllegalArgumentException: 'script' must not be null or empty 2025-07-11 15:49:05.968 INFO 11328 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated... 2025-07-11 15:49:05.974 INFO 11328 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed. 2025-07-11 15:49:05.976 INFO 11328 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2025-07-11 15:49:05.983 INFO 11328 --- [ main] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2025-07-11 15:49:05.995 ERROR 11328 --- [ main] o.s.boot.SpringApplication : Application run failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Invocation of init method failed; nested exception is org.springframework.jdbc.datasource.init.UncategorizedScriptException: Failed to execute database script from resource [class path resource [schema.sql]]; nested exception is java.lang.IllegalArgumentException: 'script' must not be null or empty at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.23.jar:5.3.23] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.23.jar:5.3.23] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:745) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:420) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1317) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.6.13.jar:2.6.13] at com.example.demo.Demo1Application.main(Demo1Application.java:10) ~[classes/:na] Caused by: org.springframework.jdbc.datasource.init.UncategorizedScriptException: Failed to execute database script from resource [class path resource [schema.sql]]; nested exception is java.lang.IllegalArgumentException: 'script' must not be null or empty at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:305) ~[spring-jdbc-5.3.23.jar:5.3.23] at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:254) ~[spring-jdbc-5.3.23.jar:5.3.23] at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:54) ~[spring-jdbc-5.3.23.jar:5.3.23] at org.springframework.boot.jdbc.init.DataSourceScriptDatabaseInitializer.runScripts(DataSourceScriptDatabaseInitializer.java:90) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.runScripts(AbstractScriptDatabaseInitializer.java:145) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.applyScripts(AbstractScriptDatabaseInitializer.java:107) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.applySchemaScripts(AbstractScriptDatabaseInitializer.java:97) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.initializeDatabase(AbstractScriptDatabaseInitializer.java:75) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.boot.sql.init.AbstractScriptDatabaseInitializer.afterPropertiesSet(AbstractScriptDatabaseInitializer.java:65) ~[spring-boot-2.6.13.jar:2.6.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863) ~[spring-beans-5.3.23.jar:5.3.23] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800) ~[spring-beans-5.3.23.jar:5.3.23] ... 18 common frames omitted Caused by: java.lang.IllegalArgumentException: 'script' must not be null or empty at org.springframework.util.Assert.hasText(Assert.java:289) ~[spring-core-5.3.23.jar:5.3.23] at org.springframework.jdbc.datasource.init.ScriptUtils.splitSqlScript(ScriptUtils.java:636) ~[spring-jdbc-5.3.23.jar:5.3.23] at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:252) ~[spring-jdbc-5.3.23.jar:5.3.23] ... 28 common frames omitted 进程已结束,退出代码为 1 解释是什么意思并给出解决方法
07-12
<think>我们正在处理Spring Boot启动失败的问题,错误信息指出在初始化数据库时找不到`schema.sql`脚本。根据引用内容,Spring Boot 2.6.x版本中数据库初始化的配置方式有所变化。下面将详细解释错误原因并提供解决方法。 ### 错误原因分析 1. **配置变更**:在Spring Boot 2.6.x版本中,`spring.datasource.schema`和`spring.datasource.data`属性已被弃用[^1]。新的配置方式使用`spring.sql.init`属性。 2. **默认行为**:Spring Boot默认会在启动时从`classpath`根目录查找`schema.sql`和`data.sql`文件来初始化数据库。但错误信息显示没有找到`schema.sql`文件。 3. **非嵌入式数据库**:如果使用的是非嵌入式数据库(如MySQL),默认情况下Spring Boot不会自动执行SQL初始化脚本,除非显式配置[^2]。 ### 解决方法 #### 步骤1:确认SQL文件位置 确保你的SQL文件(如`schema.sql`)位于`src/main/resources`目录下。如果是多模块项目,请确保文件在正确模块的资源目录中。 #### 步骤2:更新配置文件 在`application.properties`或`application.yml`中配置SQL初始化属性: **application.properties配置示例:** ```properties # 启用SQL初始化 spring.sql.init.mode=always # 指定schema脚本位置(可选,默认是schema.sql) spring.sql.init.schema-locations=classpath:schema.sql # 指定数据脚本位置(可选,默认是data.sql) spring.sql.init.data-locations=classpath:data.sql ``` **application.yml配置示例:** ```yaml spring: sql: init: mode: always schema-locations: classpath:schema.sql data-locations: classpath:data.sql ``` #### 步骤3:针对非嵌入式数据库 如果使用MySQL、PostgreSQL等非嵌入式数据库,必须显式设置`spring.sql.init.mode=always`才能执行初始化脚本[^2]。 #### 步骤4:验证文件内容 确保`schema.sql`文件不为空且包含有效的SQL语句。例如: ```sql CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, email VARCHAR(50) UNIQUE NOT NULL ); ``` #### 步骤5:清理与重建 如果之前构建过项目,请清理并重新构建: - Maven项目:执行`mvn clean package`后再运行 - IDE中:使用`Build > Rebuild Project`功能 ### 补充说明 - **多脚本支持**:可以指定多个脚本,用逗号分隔: ```yaml spring.sql.init.schema-locations: classpath:db/schema1.sql,classpath:db/schema2.sql ``` - **平台特定脚本**:Spring Boot支持根据数据库平台自动选择脚本,例如`schema-mysql.sql`,当检测到MySQL数据库时会自动使用该脚本[^3]。 ### 验证是否成功 启动应用时,观察日志中是否出现类似以下信息: ``` Initializing database with script from [file:.../schema.sql] Executing SQL script from class path resource [schema.sql] ``` ### 常见问题排查 1. **文件位置错误**:确认`schema.sql`位于`src/main/resources`目录,构建后会在`target/classes`下出现。 2. **配置未生效**:检查是否在正确的profile配置文件中设置了属性。 3. **版本兼容性**:确保所有Spring Boot依赖版本一致(当前为2.6.13)。 通过以上步骤,应该能解决数据库初始化失败的问题。如果问题仍然存在,请检查数据库连接配置是否正确,以及数据库用户是否有执行DDL语句的权限。 §§相关问题§§ 1. 如何在Spring Boot中配置多数据源并分别初始化SQL脚本? 2. Spring Boot 2.6.x中数据库初始化配置与旧版本有何区别? 3. 如何为不同的数据库平台(如MySQL、PostgreSQL)提供不同的初始化脚本?</think>### Spring Boot启动失败:`'dataSourceScriptDatabaseInitializer'`初始化失败解决方案 #### 问题原因分析 1. **配置变更**:Spring Boot 2.6.x版本弃用了旧的`spring.datasource.schema`配置方式[^1] 2. **文件位置错误**:应用在classpath根目录(`src/main/resources/`)找不到`schema.sql`文件 3. **初始化模式未启用**:对于非嵌入式数据库(如MySQL),需要显式启用SQL初始化 4. **脚本路径不匹配**:实际SQL文件位置与配置路径不一致 #### 解决方法 ##### 1. 更新配置文件(关键步骤) 在`application.yml`中使用新的配置语法: ```yaml spring: sql: init: mode: always # 强制启用SQL初始化 schema-locations: classpath:db/schema.sql # 自定义路径 data-locations: classpath:db/data.sql # 可选数据脚本 ``` ##### 2. 验证文件位置 确保SQL文件在正确位置: ``` src/main/resources/ ├── application.yml └── db/ ├── schema.sql # 表结构脚本 └── data.sql # 初始数据脚本(可选) ``` ##### 3. 检查SQL文件内容 确认`schema.sql`不为空且语法正确(示例): ```sql -- schema.sql CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(50) NOT NULL, email VARCHAR(100) UNIQUE ); ``` ##### 4. 清理并重建项目 ```bash mvn clean package # Maven项目 # 或 ./gradlew clean build # Gradle项目 ``` ##### 5. 验证配置生效 启动时观察日志,成功时会显示: ``` Initializing database with script from [file:.../db/schema.sql] Executed SQL script from class path resource [db/schema.sql] ``` #### 不同场景处理方案 | 场景 | 配置方案 | |------|----------| | **嵌入式数据库** (H2) | 无需`mode: always`,自动执行 | | **外部数据库** (MySQL) | 必须设置`mode: always` | | **多环境配置** | 使用`spring.profiles.active`指定环境专属脚本 | | **平台特定脚本** | 命名如`schema-mysql.sql`自动匹配 | #### 完整配置示例 ```yaml # application.yml spring: profiles: active: dev # 环境配置 sql: init: mode: always schema-locations: - classpath:db/${spring.profiles.active}/schema.sql data-locations: - classpath:db/${spring.profiles.active}/data.sql datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: securePass123 ``` #### 故障排查步骤 1. **检查文件是否存在**: ```bash # 查看构建后的文件位置 ls target/classes/db/schema.sql ``` 2. **启用详细日志**: ```yaml logging: level: org.springframework.jdbc.datasource.init: DEBUG ``` 3. **手动测试脚本执行**: ```java @SpringBootTest class SqlInitTest { @Autowired DataSource dataSource; @Test void testSchemaLoad() throws SQLException { try (Connection conn = dataSource.getConnection(); Statement stmt = conn.createStatement()) { stmt.execute("SELECT * FROM users"); // 验证表是否存在 } } } ``` > **重要提示**:Spring Boot 2.5+版本必须使用`spring.sql.init`替代弃用的`spring.datasource.schema`配置[^1][^2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值