实体类读取yml中的配置

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方法来注入属性的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值