现在开发主要使用微服务框架springboot,在springboot中经常遇到读取application.yml文件的情形。
一、概述
开发过程中经常遇到要读取application.yml文件中的属性值,本文总结几种读取的方式,供参考。
二、详述
我这里使用的是springboot-2.1.2.RELEASE版本,这里使用的是application.properties的配置方式,和使用application.yml的方式是一样的。下面是application.properties文件的内容
cn.com.my.test1=test1
cn.com.my.test2=test2
1、@Value注解
这种方式是spring最早提供的方式,通过@Value注解的方式,该注解用在属性上,但是要求该属性所在的类必须要被spring管理。
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TestController {
@Value("${cn.com.my.test1}")
private String test1;
@Value("${cn.com.my.test2}")
private String test2;
@RequestMapping("/test1/test")
@ResponseBody
public String getTest(){
return "hello:"+test1+",test2:"+test2;
}
}
在标记有@Controller类中使用了带有@Value注解的test1和test2的属性,首先标记有@Controller注解便可以使该类被spring管理。其次,使用@Value标记了属性,则可以获得application.properties(application.yml)文件中的属性,这里使用${cn.com.my.test1},属性的名称必须是全部的名称,测试结果如下,