在Spring-Boot中如何使用@Value注解注入集合类
我们在使用spring框架进行开发时,有时候需要在properties文件中配置集合内容并注入到代码中使用。本篇文章的目的就是给出一种可行的方式。
1.注入通常来说,我们都使用@Value注解来注入properties文件中的内容,注入集合类时,我们也使用@Value来注入。
properties文件中的内容如下:my.set=foo,barmy.list=foo,barmy.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 { @Autowired private ClassUsingProperties classUsingProperties; @Test public void testInjectCollectionFieldsUsingPropertiesFile() {Map<String, String> map = classUsingProperties.getMap();Set<String> set = classUsingProperties.getSet();List<String> list = classUsingProperties.getList();asserts(map, set, list); } private void asserts(Map<String, String> map, Set<String> set, List<String> list) {Assert.assertEquals(map.get('foo'), 'bar');Assert.assertTrue(set.contains('foo'));Assert.assertTrue(set.contains('bar'));Assert.assertTrue(list.contains('foo'));Assert.assertTrue(list.contains('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。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持好吧啦网。
相关文章:
