SpringBoot整合yml

.properties这个配置文件比.yml配置文件冗余,用yml文件会显得更加整洁美观

两个配置文件语法对比

具体写法如下

首先创建一个后缀.yml的文件

##定义自己的配置文件 不要直接定义字段,这样不好,在配置字段前面可以加上团队名称或者框架名称
## xyt:团队名称,userName/age字段名  注意每个层级之间的缩进,
##冒号(:)后面一定要跟个空格,正确的语法是 定义的字段颜色是深蓝色的,后面的值是灰色的。
xyt:
  userName: 菜鸟学习Springboot的第N天
  age: 22

创建一个类读取自己在配置文件定义的字段


import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @Value("${xyt.userName}")//@Value读取配置文件的字段,xyt:团队名称或者框架名称,userName配置文件的字段名
    private String userName;

    @Value("${xyt.age}")
    private String age;


    @RequestMapping("/getValue")
    public String getValue() {
        return userName + ",年龄:" + age;
    }
}

多环境配置文件

例子:

公司的配置文件都是分类

  • dve本地开发环境
  • test服务器测试环境
  • pre预生产环境
  • prod正式生产环境

application-dve.yml

##本地开发环境
xyt:
  userName: 本地开发环境
  url: dve.xyt.com

application-test.yml

##测试环境配置
xyt:
  userName: 测试环境
  url: test.xyt.com

application-pre.yml

##预生产环境配置
xyt:
  userName: 预生产环境
  url: pre.xyt.com

application-prod.yml

##正式环境
xyt:
  userName: 正式环境
  url: prod.xyt.com

读取配置文件的信息


@RestController
public class IndexController {

    @Value("${xyt.userName}")//xyt.userName  配置文件里:xyt+userName
    private String userName;

    @Value("${xyt.url}")
    private String url;

    @RequestMapping("/getUrl")
    public String gerUrl() {

        return userName + ":" + url;
    }
}

启动代码:

package com.xyt.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AppSpringBootMybatis {
    public static void main(String[] args) {
        SpringApplication.run(AppSpringBootMybatis.class, args);
    }
}

启动结果

发布了31 篇原创文章 · 获赞 1 · 访问量 6527
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章