目錄
@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;
}
}