SpringBoot:yml文件给变量赋值以及test的使用

有一个student类,其中变量如下,下面在application.yml文件中进行赋值。注意,application.yml中,用冒号表示赋值,并且赋值的冒号后面必须要有一个空格。

#application.yml中的配置
student:
  name: chen
  age: 23
  sex: true
  hobbies:  #hobbies是个数组,数组和list都用这种方法赋值,-后面要有空格
    - book
    - music
    - run
  location: {province: 贵州,city: 毕节,zone: 七星关区}  #map类型的写法
  skills:   #skills是个list
    - math
    - codding
    - running
  pet:
    name: hashiqi
    color: white

 现在要将student类和yml文件关联起来,在student类前面加上@Component@ConfigurationProperties(prefix = "student")注解(给对象注入值都加上这两个注解)。然后在test中打印出配置的值。

右键运行DemoApplicationTests,运行结果如下:

注意:添加注解后,可能会有依赖警告,到时候在pom.xml文件中加入以下依赖即可

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
发布了126 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36880027/article/details/104344206
今日推荐