詳解 Spring注解的(List&Map)特殊注入功能
最近接手一個新項目,已經沒有原開發人員維護了。項目框架是基于spring boot進行開發。其中有兩處Spring的注解花費了大量的時間才弄明白到底是怎么用的,這也涉及到spring注解的一個特殊的注入功能。
首先,看到代碼中有直接注入一個List和一個Map的。示例代碼如下:
@Autowiredprivate List<DemoService> demoServices;@Autowiredprivate 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. */@Servicepublic 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已經幫我們做了很多事情,只是我們不知道而已。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答