栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

读取yaml文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

读取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 !";
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/939876.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号