读取/加载/配置yml文件

本文介绍了YAML(.yml)文件格式在SpringBoot中的应用,包括基本语法、配置示例以及如何使用`@ConfigurationProperties`和`@Component`注解。还讨论了导入YML依赖和处理配置问题的方法。
部署运行你感兴趣的模型镜像

简介yml文件

  • yml 文件格式是YAML编写的文件格式
  • 是一种直观的能够被电脑识别数据序列化格式
  • 以.yml为后缀的文件
  • 容易被人类阅读,容易和脚本语言交互
  • 可以被支持YAML库的不同的编程语言程序导入,比如:C/C++,Python,Java,Ruby,C#等

yml文件格式

基本语法:

  1. k: v表示键值对关系,冒号后面必须带一个空格。
  2. 空格的缩进表示层级关系,只要是左对齐,就都表示同一级
  3. 大小写敏感
  4. 数组写法有两种
  5. 双引号不会转义字符串里面的特殊字符,而单引号会转义字符串里面的特殊字符,特殊字符最终是一个普通的字符串数据
​
  k: [v1,v2,v3]
  k1:
    - v1
    - v2
    - v3
  k3: {a: v1,b: v2, c: v3}

​

注意,这里逗号为英文逗号

配置yml文件 

person:
  name: 张三
  age: 20
  date: 2002/11/30
  interests: [编程,小说,漫画,年代剧,弓箭,骑马]
  animals:
    - 舔狗
    - 小丑
    - 沸羊羊

在pom.xml中导入yml依赖

 <!--加载yml资源-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

如果依赖没有导入,会在加载资源类的时候提醒你

准备资源配置类 

@ConfigurationProperties(prefix="person")
@Configuration
@Component
public class YkConfigProperty {
    private String name;
    private Integer age;
    private Date date;
    private List<String> interests;
    private String[] animals;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public List<String> getInterests() {
        return interests;
   }
   public void setInterests(List<String> interests) {
       this.interests = interests;
   }

    public String[] getAnimals() {
        return animals;
    }

    public void setAnimals(String[] animals) {
        this.animals = animals;
    }
 @Bean
    public  void load(){
        System.out.println("name='" + name + '\'' +
                ", age=" + age +
                ", date=" + date +
                ", interests=" + interests +
                ", animals=" + Arrays.toString(animals));
    }

结果展示: 

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::               (v2.7.15)

2023-08-30 13:45:35.009  INFO 10716 --- [           main] com.example.yk.YkApplication             : Starting YkApplication using Java 1.8.0_352 on DESKTOP-480FVQ7 with PID 10716 (D:\javaxiangmu\yk\target\classes started by yk in D:\javaxiangmu\yk)
2023-08-30 13:45:35.014  INFO 10716 --- [           main] com.example.yk.YkApplication             : No active profile set, falling back to 1 default profile: "default"
2023-08-30 13:45:36.159  INFO 10716 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2023-08-30 13:45:36.167  INFO 10716 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-08-30 13:45:36.167  INFO 10716 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.79]
2023-08-30 13:45:36.261  INFO 10716 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-08-30 13:45:36.262  INFO 10716 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1183 ms
name='张三', age=20, date=Sat Nov 30 00:00:00 CST 2002, interests=[编程, 小说, 漫画, 年代剧, 弓箭, 骑马], animals=[舔狗, 小丑, 沸羊羊]
2023-08-30 13:45:36.594  INFO 10716 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2023-08-30 13:45:36.604  INFO 10716 --- [           main] com.example.yk.YkApplication             : Started YkApplication in 2.201 seconds (JVM running for 3.515)

遇到问题及解决

Description:

Failed to bind properties under 'person.date' to javax.xml.crypto.Data:

    Property: person.date
    Value: "2002/11/30"
    Origin: class path resource [application.yml] - 4:9
    Reason: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [javax.xml.crypto.Data]

Action:

Update your application's configuration

这里告诉我们person.date存在问题,在application.yml文件里找4-9行, 这里主要是导入的类导错了,没有把data和date搞清楚,正确的应该是java.util.Date

同理,如果以后遇到类似问题:要么去查看导入的类是否正确,或者查看yml文件对应的错误位置格式是否书写正确,是少了字母,还是大小写符号有误

最后总结

@ConfigurationProperties(prefix="person")
@Configuration
@Component

@ConfigurationProperties(prefix=" person"),它的意思是读取properties中所有以person开头的属性,并且与@Bean中的字段进行匹配

@Configuration注解标识的类中声明一个或者多个Bean方法

@Component注解:标识Spring管理的Bean,使用@Component注解在一个类上,表示将此类标示为Spring容器的一个Bean

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

<think> 根据用户的问题,用户遇到了在使用`--spring.config.location=./yml/application.yml`时无法正确引用外部配置文件的问题。结合站内引用,我们需要分析可能的原因并提供解决方案。 站内引用中提到了几种使用外部配置文件的方式: 1. 使用`--spring.config.location`指定配置文件路径(如引用[2]和引用[3]所示) 2. 使用`--spring.config.additional-location`来添加额外的配置文件(如引用[4]所示) 用户当前使用的是`--spring.config.location=./yml/application.yml`,但未生效。可能的原因有: 1. 路径不正确:`./yml/application.yml`是相对路径,可能相对于当前工作目录,而用户执行命令时的工作目录可能不是该jar包所在的目录。 2. 配置文件的命名和格式问题:Spring Boot默认加载配置文件名为`application`,且支持properties和yml格式。如果指定的文件名不是默认的`application`,则可能不会被加载。 3. 配置项覆盖问题:如果同时存在多个配置文件,可能会有覆盖的情况。 根据引用[1]中提到的背景和默认加载顺序,以及引用[3]中提到的在jar文件目录下放置配置文件的方式,我们可以提供以下解决方案: **解决方案1:使用绝对路径** 将相对路径改为绝对路径,确保路径正确无误。 ```bash --spring.config.location=/absolute/path/to/yml/application.yml ``` **解决方案2:改变相对路径的基准** 如果坚持使用相对路径,需要确保命令是在正确的目录下执行。假设jar包在`/app`目录,而配置文件在`/app/yml/application.yml`,那么执行命令时应该在`/app`目录下,使用: ```bash --spring.config.location=yml/application.yml ``` 注意:这里没有`./`,因为当前目录就是jar所在目录。或者使用`file:`前缀: ```bash --spring.config.location=file:./yml/application.yml ``` **解决方案3:使用`--spring.config.additional-location`** 根据引用[4],可以使用`--spring.config.additional-location`来添加额外的配置文件,这样不会覆盖默认的加载位置,而是追加。 ```bash --spring.config.additional-location=./yml/application.yml ``` **解决方案4:检查配置文件名称和格式** 确保配置文件的名称是`application`,且扩展名正确(.yml或.properties)。如果文件名为其他,则需要指定完整的文件名(包括扩展名),且需要确保Spring Boot能够识别。 **解决方案5:使用目录方式指定** 如果指定的是一个目录,Spring Boot会在该目录下查找默认的配置文件(即application.yml或application.properties)。因此,也可以指定目录: ```bash --spring.config.location=./yml/ ``` **注意事项:** - 在Windows系统中,路径分隔符使用`\`,但最好使用`/`或双反斜杠`\\`,例如:`--spring.config.location=file:C:\\path\\to\\yml\\application.yml` - 如果同时指定多个位置,用逗号分隔,如引用[2]和引用[4]所示。 **验证配置是否生效:** 可以在配置文件中设置一个特定的属性(如:test.property=123),然后在应用启动后检查该属性是否被正确加载。 **示例命令:** 结合用户之前的启动命令,修改后的命令可能如下(使用解决方案3): ```bash mkdir -p ./log && lsof -i:7001 -t | xargs -r kill -9; sleep 2; nohup java -Xms256m -Xmx512m -jar "stroe-management-1.0-SNAPSHOT.jar" --spring.config.additional-location=./yml/application.yml > "./log/app_$(date +'%Y%m%d_%H%M%S').log" 2>&1 & ``` 如果问题仍然存在,建议检查: - 配置文件读取权限 - 配置文件的格式是否正确(YAML格式要求严格,注意缩进) 根据引用[1]中提到的“spring.config.location为什么没有生效”,可能的原因还包括在配置文件中设置了`spring.config.location`属性,这会导致命令行参数被覆盖。因此,确保不要在配置文件中设置该属性。 如果以上方法都不能解决,可以尝试使用`spring.config.name`参数来指定配置文件的名称(如果文件名不是application): ```bash --spring.config.name=myconfig --spring.config.location=./yml/ ``` 这样会加载`./yml/`目录下的`myconfig.yml`文件。 最后,建议用户查看Spring Boot官方文档关于外部化配置的部分,以获取最新信息。 §§相关问题§§ 1. Spring Boot配置文件加载顺序是怎样的? 2. 如何同时使用多个配置文件(如多环境配置)? 3. Spring Boot中如何配置Profile-specific的外部配置文件? 4. 如何通过环境变量设置Spring Boot配置? 5. 在Docker容器中如何正确挂载Spring Boot配置文件? </think> 针对 `--spring.config.location=./yml/application.yml` 无法正确加载外部配置文件的问题,结合引用内容提供以下解决方案: ### 问题原因分析 1. **路径格式问题**(引用[2][3]) Spring Boot 对路径格式有严格要求: - 相对路径 `./yml/` 可能未正确解析 - 需要显式添加 `file:` 前缀或使用绝对路径 2. **配置覆盖机制**(引用[1][4]) 使用 `spring.config.location` 会**完全替代**默认配置加载路径,导致: ```properties # 默认的 application.yml 将被忽略 classpath:/,classpath:/config/,file:./,file:./config/ ``` 3. **目录与文件混淆**(引用[3]) 参数应指向具体文件而非目录: ```diff - --spring.config.location=./yml/ # 错误:目录 + --spring.config.location=./yml/application.yml # 正确:具体文件 ``` ### 解决方案 #### ✅ 方案1:添加 `file:` 前缀(推荐) ```bash java -jar your_app.jar \ --spring.config.location=file:./yml/application.yml ``` > 关键点:`file:` 前缀明确指示文件系统路径[^2][^3] #### ✅ 方案2:使用绝对路径 ```bash java -jar your_app.jar \ --spring.config.location=/home/user/app/yml/application.yml ``` > 优势:避免相对路径歧义[^3] #### ✅ 方案3:改为 `additional-location`(最佳实践) ```bash java -jar your_app.jar \ --spring.config.additional-location=./yml/application.yml ``` > 优势: > 1. 追加而非替换默认配置路径[^4] > 2. 保留默认配置文件加载能力 > 3. 支持多文件合并配置(优先级:命令行 > 外部文件 > 内部文件) #### ✅ 方案4:目录级指定(需包含文件名) ```bash # 显式包含文件java -jar your_app.jar \ --spring.config.location=classpath:/,file:./yml/application.yml ``` ### 调试步骤 1. **验证路径** ```bash # 检查文件是否存在 ls -l ./yml/application.yml # 输出示例 -rw-r--r-- 1 user group 1024 Jan 01 12:00 ./yml/application.yml ``` 2. **启用配置调试** 启动时添加参数: ```bash java -jar your_app.jar \ --debug \ --spring.config.location=file:./yml/application.yml ``` 在日志中搜索: ```log Config resource locations [file:./yml/application.yml] Loaded config file [file:./yml/application.yml] ``` 3. **路径规范建议** | 路径类型 | 正确格式示例 | 错误格式示例 | |----------------|----------------------------------|---------------------| | 相对路径 | `file:./config/app.yml` | `./config/app.yml` | | 绝对路径 | `/etc/app/config.yml` | `~/app/config.yml` | | 多文件组合 | `file:./cfg1.yml,file:./cfg2.yml`| 无逗号分隔 | ### 配置加载优先级(引用[1][4]) 当存在多个配置源时,按以下顺序覆盖: ```mermaid graph LR A[命令行参数] --> B[additional-location] B --> C[spring.config.location] C --> D[Jar包内application.yml] D --> E[默认系统配置] ``` > 经验法则: > - 需要**完全自定义**配置路径 → 用 `spring.config.location` > - 需要**追加**配置 → 用 `spring.config.additional-location`[^4] > - 生产环境建议使用**绝对路径**
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值