无为清净楼资源网 Design By www.qnjia.com
详解 Spring注解的(List&Map)特殊注入功能
最近接手一个新项目,已经没有原开发人员维护了。项目框架是基于spring boot进行开发。其中有两处Spring的注解花费了大量的时间才弄明白到底是怎么用的,这也涉及到spring注解的一个特殊的注入功能。
首先,看到代码中有直接注入一个List和一个Map的。示例代码如下:
@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代码:
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代码:
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 执行结果如下:
我被调用了 ===============分割线============= 我被调用了
原来,在不知不觉中Spring已经帮我们做了很多事情,只是我们不知道而已。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com
暂无评论...
更新日志
2024年09月20日
2024年09月20日
- 青稞荞麦《破茧》新生代组合[WAV+CUE]
- 因系统升级后出现BUG 《FF16》PS5完全版宣布延期
- 《黑神话:悟空》周伯通!大佬用左右手分别挑战两只虎先锋
- 《黑神话:悟空》攻击动作致敬《大话西游》:这也太帅了!
- 《星舰铳犬太阳系物语》游戏背景介绍
- 《战锤40K星际战士2》终极版有后续DLC说明
- 《第9层》游戏特色玩法介绍
- 刀郎.2006-刀郎【九雨天下】【WAV+CUE】
- 59.9高校生.1994-素兰万岁【上华】【WAV+CUE】
- ECHO.1991-你是爱我还是需要我(国专)【EMI百代】【WAV+CUE】
- 交错战线零课主线困难通关阵容推荐一览
- 交错战线挖掘矿场角色推荐攻略
- 命运圣契公测平民阵容怎么搭配 新手开荒平民阵容攻略
- 金梅《现代发烧的声音2》发烧碟[WAV+CUE]
- 雨果唱片-《历史录音珍藏系列-现代芭蕾舞剧·红色娘子军》2CD【WAV】