Springboot中獲取配置檔案(application.yml)中自定義的變數並使用
阿新 • • 發佈:2021-09-04
前言:在寫專案中我們經常要將同樣的變數在不同的檔案中寫無數次,這樣修改起來要一通好找,非常不方便,平常都會寫一個工具類存入自己的變數進行呼叫取值,但是呢,懶得寫咋辦,寫了還要注入,注入失敗又得.........麻煩,有沒有辦法寫在配置檔案中直接自定義變數通過註解的方式取值呢?肯定有啊。
正文:
一、在application.yml中配置自己的變數比如:
person: name: '張三' age: '年齡25' home: '擁有房子1套' car: '轎車1輛'
二、使用註解取值並且使用
import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/test") public class TestController { @Value("${person.name}") private String name; @Value("${person.age}") private String age; @Value("${person.home}") private String home; @Value("${person.car}") private String car; @RequestMapping("/getsome") public String getSome(){ System.out.println(name+age+home+car); return name+age+home+car; } }
三、在瀏覽器訪問檢視效果
可以看到完全可以通過註解的方式直接取值使用,非常方便。