Spring Boot的配置文件

通过Spring Boot的配置文件,可以对其进行配置,其配置文件有properties和yaml,也有其他第三方配置。
例如以下,可更改SpringApplication的访问端口和上下文路径

server.port=80
server.servlet.context-path=/grade

除此之外,可自定义配置属性,并可通过@Value和@ConfigurationProperties来获取属性的值。

  1. @Value的使用
    @Value的使用格式为@Value("${属性值}"),示例如下

application.properties配置文件

server.port=80
grade.name=xiaoming
grade.degree=B

控制器的内容

package com.imooc.demo;

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

@RestController
public class GradeController {
    @Value("${grade.name}")
    private String name;

    @Value("${grade.degree}")
    private String degree;

    @RequestMapping(value = "/grade")
    public String showGrade() {
        return this.name + "同学获得了成绩" + this.degree;
    }
}

运行后访问地址localhost/grade,可看到显示如下
运行结果
2. @ConfigurationProperties的使用
如果要把多个前缀相同的属性映射到一个对象中,可使用此注解。在你想要映射的对象加上注解即可。实例如下

application.properties配置文件

server.port=80
grade.name=xiaoming
grade.degree=B

被映射的对象,set和get方法不能缺少

package com.imooc.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "grade")
public class Grade {
    private String name;
    private String degree;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDegree() {
        return degree;
    }

    public void setDegree(String degree) {
        this.degree = degree;
    }
}

在控制器中的使用

package com.imooc.demo;

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

@RestController
public class GradeController {
    @Autowired
    private Grade grade;

    @RequestMapping(value = "/grade")
    public String showGrade() {
        return grade.getName() + "同学获得了成绩" + grade.getDegree();
    }
}

运行后结果如下
运行结果

以上两个例子的配置文件properties,可用yaml格式的配置文件代替,如下

server:
  port: 80
grade:
  name: xiaoming
  degree: B

在属性值前一定要有空格。
yaml的配置文件优点在于配置简单,但缺点在于不能使用@PropertySource注解。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值