详解 Spring注解的(List&Map)特殊注入功能
更新时间:2017年05月10日 15:29:33 作者:丑胖侠的技术生涯
这篇文章主要介绍了详解 Spring注解的(List&Map)特殊注入功能的相关资料,需要的朋友可以参考下
详解 Spring注解的(List&Map)特殊注入功能
最近接手一个新项目,已经没有原开发人员维护了。项目框架是基于spring boot进行开发。其中有两处Spring的注解花费了大量的时间才弄明白到底是怎么用的,这也涉及到spring注解的一个特殊的注入功能。
首先,看到代码中有直接注入一个List和一个Map的。示例代码如下:
1 2 3 4 5 | @Autowired private List<DemoService> demoServices; @Autowired private Map<String,DemoService> demoServiceMap; |
以上是两处代码示例化之后的demo。当时看到这里之后有些懵,全局搜索之后并没有发现定义一个List和Map的对象。然而debug运行之后却发现它们的确都有值。这个事情就有些神奇了。在网上搜索也收获甚微。
最后在调试List的时候突然灵感一闪,如果只有一个对象那么List里面的值不就只有一个吗。于是开始测试验证,结果发现的确如此。当实例化一个DemoService之后,另外一个类采用泛型注入List,Spring竟然成功的将实例化的对象放入List之中。思路打开之后,针对Map的就更好说了。Spring会将service的名字作为key,对象作为value封装进入Map。
具体事例代码如下
DemoService代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package com.secbro.learn.service; import org.springframework.stereotype.Service; /** * Created by zhuzs on 2017/5/8. */ @Service public class DemoService { public void test(){ System.out.println( "我被调用了" ); } } |
DemoController代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package com.secbro.learn.controller; import com.secbro.learn.service.DemoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; import java.util.Map; /** * Created by zhuzs on 2017/5/8. */ @Controller @RequestMapping (value = "/demo" ) public class DemoController { @Autowired private List<DemoService> demoServices; @Autowired private Map<String,DemoService> demoServiceMap; @ResponseBody @RequestMapping (value = "/test" ) public String test(){ for (Map.Entry<String,DemoService> entry : demoServiceMap.entrySet()){ entry.getValue().test(); } System.out.println( "===============分割线=============" ); for (DemoService demoService : demoServices){ demoService.test(); } return "success" ; } } |
运行之后,访问http://localhost:8080/demo/test 执行结果如下:
1 2 3 | 我被调用了 ===============分割线============= 我被调用了 |
原来,在不知不觉中Spring已经帮我们做了很多事情,只是我们不知道而已。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!