要注意的地方是 application.yml 中不能用驼峰式写法(systemparams)要改成system-params
方法一:
引入依赖:
<!-- 支持 @configurationproperties 注解 --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-configuration-processor</artifactid> <optional>true</optional> </dependency>
配置文件(application.yml)中配置各个属性的值:
myprops: #自定义的属性和值 simpleprop: simplepropvalue arrayprops: 1,2,3,4,5 listprop1: - name: abc value: abcvalue - name: efg value: efgvalue listprop2: - config2value1 - config2vavlue2 mapprops: key1: value1 key2: value2
创建一个bean来接收配置信息:
@component @configurationproperties(prefix="myprops") //接收application.yml中的myprops下面的属性 public class myprops { private string simpleprop; private string[] arrayprops; private list<map<string, string>> listprop1 = new arraylist<>(); //接收prop1里面的属性值 private list<string> listprop2 = new arraylist<>(); //接收prop2里面的属性值 private map<string, string> mapprops = new hashmap<>(); //接收prop1里面的属性值 public string getsimpleprop() { return simpleprop; } //string类型的一定需要setter来接收属性值;maps, collections, 和 arrays 不需要 public void setsimpleprop(string simpleprop) { this.simpleprop = simpleprop; } public list<map<string, string>> getlistprop1() { return listprop1; } public list<string> getlistprop2() { return listprop2; } public string[] getarrayprops() { return arrayprops; } public void setarrayprops(string[] arrayprops) { this.arrayprops = arrayprops; } public map<string, string> getmapprops() { return mapprops; } public void setmapprops(map<string, string> mapprops) { this.mapprops = mapprops; } }
启动后,这个bean里面的属性就会自动接收配置的值了。
单元测试用例:
@autowired private myprops myprops; @test public void propstest() throws jsonprocessingexception { system.out.println("simpleprop: " + myprops.getsimpleprop()); system.out.println("arrayprops: " + objectmapper.writevalueasstring(myprops.getarrayprops())); system.out.println("listprop1: " + objectmapper.writevalueasstring(myprops.getlistprop1())); system.out.println("listprop2: " + objectmapper.writevalueasstring(myprops.getlistprop2())); system.out.println("mapprops: " + objectmapper.writevalueasstring(myprops.getmapprops())); }
测试结果:
simpleprop: simplepropvalue arrayprops: ["1","2","3","4","5"] listprop1: [{"name":"abc","value":"abcvalue"},{"name":"efg","value":"efgvalue"}] listprop2: ["config2value1","config2vavlue2"] mapprops: {"key1":"value1","key2":"value2"}
方法二:
不用写 set 方法,直接给注解。
前提是要装一个插件:lombok 。 直接在插件中搜索到它,装上就行了
直接获取一个属性
image: location: d:/images/ /** * 在配置文件中配置的文件保存路径 */ @value("${image.location}") private string location;
以上这篇在springboot 中从application.yml中获取自定义常量方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
多线程、同步工作原理、死锁案例、Lock接口、线程的生命周期的讲解及实现
网友评论