读取yaml文件

SpringBoot的核心内核就是靠 起步依赖和引导类
SpringBoot配置文件:
application.properties > application.yml > application.yaml
主要使用 yml 文件

yaml文件

扩展名:yml(主流),yaml
以数据为核心,重数据,轻格式

语法规则

  1. 大小写敏感
  2. 属性值前面要有一个空格
  3. #表示注释
lesson: SpringBoot    # 记得写数据的时候前面隔个 空格
server:
  port: 80

enterprise:
  name: itcast
  age: 17
  tel: 4006184000
  subject:				# 表示一个数组
    - Java
    - 前端
    - 大数据

读取 yaml文件中的内容

第一种方式:@Value注入

@Controller
@ResponseBody
@RequestMapping("/books")
public class BookController {
    @Value("${lesson}")
    private String lesson;
    @Value("${server.port}")
    private Integer port;
    @Value("${enterprise.subject[0]}")
    private String subject_00;

    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println(id);
        System.out.println(lesson);
        System.out.println(port);
        System.out.println(subject_00);
        return "hello,Spring Boot !";
    }
}

发送请求:http://127.0.0.1/books/94
在这里插入图片描述
第二种方式,使用Environment对象(org.springframework.core.env 包下的)

@Controller
@ResponseBody
@RequestMapping("/books")
public class BookController {
    @Autowired
    private Environment en;

    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println(id);
        System.out.println(en.getProperty("lesson"));
        System.out.println(en.getProperty("server.port"));
        System.out.println(en.getProperty("enterprise.age"));
        System.out.println(en.getProperty("enterprise.subject[1]"));
        return "hello,Spring Boot !";
    }
}

在这里插入图片描述
第三种方式,常用

@Component
@ConfigurationProperties(prefix = "enterprise")		// 从配置中读属性 enterprise
public class Enterprise {
    private String name;
    private Integer age;
    private String tel;
    private String[] subject;

    @Override
    public String toString() {
        return "Enterprise{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", tel='" + tel + '\'' +
                ", subject=" + Arrays.toString(subject) +
                '}';
    }

	get,set方法
}
@Controller
@ResponseBody
@RequestMapping("/books")
public class BookController {
    @Autowired
    private Enterprise en;

    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println(id);
        System.out.println(en);
        return "hello,Spring Boot !";
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值