配置文件引入变量

2018-09-14  本文已影响0人  SaberMaycry

开发配置文件: application-dev.yml

server:
  port: 8080 # 启动端口
  servlet:
    context-path: /saber # 启动服务前缀,表示访问Controller接口时,需要假如前缀/saber

# 配置文件引入变量
saber:
  name: "Saber"
  gender: "女"
  age: 18
  content: ${saber.name} ${saber.gender} ${saber.age}

引入 SaberProperties.java

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

/**
 * 属性配置类
 */
@Component // 作为spring组件引入
@ConfigurationProperties(prefix = "saber") // 引入前缀为:saber的配置文件
public class SaberProperties {
    private String name;

    private String gender;

    private int age;

    private String content;
    
    // ...省略get/set/toString方法
}

然后就可以在其他地方直接使用该配置类了,如:SaberController.java

import com.saber.properties.SaberProperties;

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

@RestController
@RequestMapping(value = "/saber") // 表示下述接口在访问时,也需要添加/saber前缀
public class SaberController {
    private SaberProperties saberProperties;

    @Autowired // 推荐利用构造函数自动注入属性
    public SaberController(SaberProperties service) {
        this.saberProperties = service;
    }
    
    // 根据不同的业务场景使用不同的请求方式,value可以作为数组
    @GetMapping(value = {"/hello", "/hi"})
    private String saber() {
        return saberProperties.toString();
    }
}

启动服务测试,日志提示启动成功

Mapped "{[/saber/hello || /saber/hi],methods=[GET]}"

地址解析:

  1. 本机地址:http://localhost:8080
  2. 开发环境配置的前缀:第一个saber前缀 /saber
  3. Controller类配置的前缀:第二个saber前缀 /saber
  4. Get方法映射的请求地址:/hello 和 /hi

http://localhost:8080/saber/saber/hello

image

http://localhost:8080/saber/saber/hi

image
上一篇下一篇

猜你喜欢

热点阅读