平时经常会使用@Value注入yml文件中的变量,但是今天使用@Value注入一个List时却报错了,程序启动失败,报Could not resolve placeholder 'blackList' in value "${blackList}”,有点懵逼。
Yml中尝试过行内和行外两种写法,都不行
行内:
blackList: 127.0.0.1,192.0.0.1
行外:
blackList:
- 127.0.0.1
- 192.0.0.1
代码注入:
@Value("${blackList}")
private String[] blackList;
网上搜了很多如何通过yml注入List,大多都是@ConfigurationProperties的方式将变量注入类的属性中。这时候上面的写法是可以注入成功的。但是我不想因为注入一个参数就编写一个类。
后来看到有文章说@Value和@ConfigurationProperties在注入数组时行为是不同的。
@Value and @ConfigurationProperties behave differently when binding to arrays
后来看到大牛的方案试了下,果然可以,太厉害了,记录膜拜下
@Value("#{'${blackList}'.split(',')}")
private List<String> blackList;
除了List不能@Value直接注入,Map也是,这里也贴出Map的转换方法:
@Value("#{${paramMaps}}")
private Map<String,String> paramMaps;
Yml:
blackList: 127.0.0.1,192.0.0.1
paramMaps: "{userId: 'u123', seckillId: 'g00001'}"
至此,问题解决!
可以看到上面我们使用了spring的表达式#{},功能还是很强大的,有兴趣可以深入了解下。@Value至此springEL,但是@ConfigurationProperties是不支持的。