目录
@ConfigurationProperties注解注入Map、List
@ConfigurationProperties注解注入Map、List
一般情况下,配置string用@value就可以实现。
@Value("${excel.must-fill-columns.title}")
private String title;
...
...
关于我的业务:在yml中配置关于excel必填列,存在多张表单的excel
在yml配置中list的话,格式是
list:
- topic1
- topic2
- topic3
显然我不喜欢.....
但是如果用map的方式,可以实现list的数据结构,就方便很多了
引入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
yml配置(配置的是map,通过在配置类用将map数据转成list)
#excel必填列参数
excel-columns:
user: {MustFillColumns: '1,6,8,9,11'}
position: {MustFillColumns: '1'}
配置类(将map数据转成list)
/**
* @Description 要注入配置文件值的类,必须是springBean,即使用@Component、@Service、@Controller等注解的类
* @Author by mocar小师兄
* @Date 2020/5/29 18:43
**/
@Component
@ConfigurationProperties(prefix = "excel-columns")
@PropertySource(value = {"classpath:/application.yml"}, encoding = "utf-8")
@Setter
//get方法自己写,将map转list
public class ExcelObjMustFillColumnConfig {
private Map<String,String> user;
private Map<String,String> position;
public List<Integer> getUser() {
List<Integer> retList = new ArrayList<>();
user.values().forEach(vo->{
ArrayList<String> strings = new ArrayList<>(Arrays.asList(vo.split(",")));
strings.forEach(str->{
retList.add(Integer.parseInt(str));
});
});
return retList;
}
public List<Integer> getPosition() {
List<Integer> retList = new ArrayList<>();
position.values().forEach(vo->{
ArrayList<String> strings = new ArrayList<>(Arrays.asList(vo.split(",")));
strings.forEach(str->{
retList.add(Integer.parseInt(str));
});
});
return retList;
}
}
测试:
@Test
public void testYml(){
excelObjMustFillColumnConfig.getUser().forEach(vo-> System.out.println(vo));
excelObjMustFillColumnConfig.getPosition().forEach(vo-> System.out.println(vo));
}
结果:
成功!
使用@Value给静态变量注入值
@Component//第一步:静态变量注入属性值需要将bean注入到ioc
public class SnowFlakeGenerateIDUtils {
public static long currentWorkerId;//当前机器
public static long currentDatacenterId;//当前机房
public static long currentSequence;//当前序列号
//第二步:需要提供set方法,且set方法不能是static,不然yml属性值无法注入,可以自测下
@Value("${snow-id.currentWorkerId}")
public void setCurrentWorkerId(long currentWorkerId) {
SnowFlakeGenerateIDUtils.currentWorkerId = currentWorkerId;
}
@Value("${snow-id.currentDatacenterId}")
public void setCurrentDatacenterId(long currentDatacenterId) {
SnowFlakeGenerateIDUtils.currentDatacenterId = currentDatacenterId;
}
@Value("${snow-id.currentSequence}")
public void setCurrentSequence(long currentSequence) {
SnowFlakeGenerateIDUtils.currentSequence = currentSequence;
}
}