在Spring-Boot中如何使⽤@Value注解注⼊集合类
我们在使⽤spring框架进⾏开发时,有时候需要在properties⽂件中配置集合内容并注⼊到代码中使⽤。本篇⽂章的⽬的就是给出⼀种可⾏的⽅式。
1.注⼊
通常来说,我们都使⽤@Value注解来注⼊properties⽂件中的内容,注⼊集合类时,我们也使⽤@Value来注⼊。
properties⽂件中的内容如下:
my.set=foo,bar
my.list=foo,bar
my.map={"foo": "bar"}
分别是我们要注⼊的Set,List,Map中的内容。
注⼊⽅式如下:
@Value("#{${my.map}}")
private Map<String, String> map;
@Value("#{'${my.set}'}")
private Set<String> set;
@Value("#{'${my.list}'}")
private List<String> list;
2.验证
我们写⼀个单测类来验证上⾯的注⼊是否可⾏。
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE,
classes = PropertiesTest.ClassUsingProperties.class)
@TestPropertySource(locations = "classpath:test.properties")
public class PropertiesTest {
spring怎么读取properties@Autowired
private ClassUsingProperties classUsingProperties;
@Test
public void testInjectCollectionFieldsUsingPropertiesFile() {
Map<String, String> map = Map();
Set<String> set = Set();
List<String> list = List();
asserts(map, set, list);
}
private void asserts(Map<String, String> map, Set<String> set, List<String> list) {
Assert.("foo"), "bar");
Assert.ains("foo"));
Assert.ains("bar"));
Assert.ains("foo"));
Assert.ains("bar"));
}
@Data
@Component
public static class ClassUsingProperties {
@Value("#{${my.map}}")
private Map<String, String> map;
@Value("#{'${my.set}'}")
private Set<String> set;
@Value("#{'${my.list}'}")
private List<String> list;
}
}
test.properties中的内容已经在上⾯给出,位置在test⽂件夹下的resources⽂件夹下⾯(maven项⽬的⽂件夹结构)。
3.原理
在我们使⽤的@Value注解中,每⼀个开头都有个#,这其实就是说明我们使⽤了SpEL,如果直接使⽤SpEL,就是下⾯的代码:
ExpressionParser parser = new SpelExpressionParser();
Map<String, String> map =
(Map<String, String>) parser
.parseExpression({'foo':'bar'}")
.getValue(Map.class);
Set<String> set =
(Set<String>) parser
.parseExpression("'foo,bar'")
.getValue(Set.class);
List<String> list =
(List<String>) parser
.
parseExpression("'foo,bar'")
.getValue(List.class);
我们也使⽤单元测试来验证:
@Test
@SuppressWarnings("unchecked")
public void testInitCollectionUsingSpEL() {
ExpressionParser parser = new SpelExpressionParser();
Map<String, String> map =
(Map<String, String>) parser
.parseExpression("{'foo':'bar'}")
.getValue(Map.class);
Set<String> set =
(Set<String>) parser
.parseExpression("'foo,bar'")
.getValue(Set.class);
List<String> list =
(List<String>) parser
.parseExpression("'foo,bar'")
.getValue(List.class);
asserts(map, set, list);
}
asserts⽅法的代码已经在验证使⽤@Value注解⽅式的单元测试中给出。
4.总结
我们⽤@Value注解把properties⽂件中的内容注⼊了集合类,注解中以#开头,其实就是使⽤了SpEL。Spring-Boot的版本是2.2.1.RELEASE,之所以要说这个,是因为⼀开始使⽤1.x版本时⽆法注⼊Set和List。
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。