版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
1、直接使用@Value自动读取
2、使用实体类映射。
3、使用@Value在加自定义去实现。
例如:
案例一:
yml中这样配置
file:
"{serviceDir: 'D://upload/service/',catalogDir: ' D://upload/catalog/',otherDir:'D://upload/other/',excelsDir:'D://upload/excels/'}"
实体类中这样去读取:
@Value("#{${file}}")
private Map<String,String> maps;
public void setMaps(Map<String,String> maps){
this.maps=maps;
}
public Map<String,String> getMaps(){
return this.maps;
}
这样yml配置文件的内容就会被自动注入到maps中了。
案例二:
yml中这样配置
file: D://upload/
实体类中这样去读取:
@Value("${file}")
private String rootPath;
private Map<String,String> maps=new HashMap<>();
//这个注解表示在bean创建完并且赋值完之后进行的操作
@PostConstruct
void init(){
maps.put("serviceDic",rootPath+"/service/");
maps.put("catalogDic",rootPath+"/catalog/");
maps.put("otherDic",rootPath+"/other/");
}
public void setRootPath(String rootPath){
this.rootPath=rootPath;
}
public String getRootPath(){
return this.rootPath;
}
这样可以达到案例一的效果。
注意:
1、yml的冒号和属性值之间一定要有一个空格隔开。
2、一定要给类的属性添加get,set方法,还有一个无参的构造方法,因为spring是根据set方法来注入属性的。