Spring Boot项目属性配置

一、Spring Boot的属性配置文件包括两种,一种为默认的properties,另一种为yml的,yml相比于properties更为简洁,所以推荐使用yml的配置文件。

    1. properties的配置文件
    #properties的配置文
    server.port=8081
    server.context-path=/gril
  1. yml的配置文件
    server:
      port: 8080
      context-path: /gril

以上两种配置方式作用相同,效果一致,使用时选择其中一种即可。

二、引用yml中的属性

  1. yml文件
    server:
      port: 8080
    cupSize: B

  2. java
       /**
         * 通过注解将配置文件cupSize里的内容注入到cupSize属性
         */
        @Value("${cupSize}")
        private String cupSize;
        //运行打印结果
       @RequestMapping(value = "/hello",method = RequestMethod.GET)
        public String say() {
            return cupSize;
        }

        注意:配置文件里的属性和server同级才可这样引用,否则无法启动项目

三、这么写配置有点累,有一个属性要写一个,有10个或更多呢?有没有一种办法让我们只写一次就可以呢?当然有。那么如何把配置写到一个类里面去?代码如下。

  1. yml
    server:
      port: 8080
    gril:
      cupSize: B
      age: 18
      context: "cupSize:${cupSize},age:${age}"

  2. GrilProperties
    /**
     * ConfigurationProperties注解获取前缀是gril的配置
     */
    @Component
    @ConfigurationProperties(prefix = "gril")
    public class GrilProperties {
        private String cupSize;
    
        private Integer age;
    
        public String getCupSize() {
            return cupSize;
        }
    
        public void setCupSize(String cupSize) {
            this.cupSize = cupSize;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    }
    

  3. 引用配置HelloController
    @RestController
    public class HelloController {
       @Autowired
       private GrilProperties grilProperties;
        //运行打印结果
       @RequestMapping(value = "/hello",method = RequestMethod.GET)
        public String say() {
            return grilProperties.getCupSize();
        }
    }

四、多环境配置:在开发环境和生产环境需要使用不同的配置,但不可能一直改配置,这是怎么办呢?开发环境一个配置文件生产环境一个配置文件,然后用总的配置文件引用

  1. 开发环境
    #  开发环境
    server:
      port: 8080
    gril:
      cupSize: B
      age: 18
      context: "cupSize:${cupSize},age:${age}"

  2. 生产环境
    #  生产环境
    server:
      port: 8081
    gril:
      cupSize: F
      age: 18
      context: "cupSize:${cupSize},age:${age}"

  3. 总的配置
    spring:
      profiles:
      # active: prod 生产环境
      # active: dev 开发环境
        active: prod



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值