詳解 Spring注解的(List&Map)特殊注入功能
詳解 Spring注解的(List&Map)特殊注入功能
最近接手一個新項目,已經(jīng)沒有原開發(fā)人員維護了。項目框架是基于spring boot進行開發(fā)。其中有兩處Spring的注解花費了大量的時間才弄明白到底是怎么用的,這也涉及到spring注解的一個特殊的注入功能。
首先,看到代碼中有直接注入一個List和一個Map的。示例代碼如下:
@Autowired private List<DemoService> demoServices; @Autowired private Map<String,DemoService> demoServiceMap;
以上是兩處代碼示例化之后的demo。當(dāng)時看到這里之后有些懵,全局搜索之后并沒有發(fā)現(xiàn)定義一個List和Map的對象。然而debug運行之后卻發(fā)現(xiàn)它們的確都有值。這個事情就有些神奇了。在網(wǎng)上搜索也收獲甚微。
最后在調(diào)試List的時候突然靈感一閃,如果只有一個對象那么List里面的值不就只有一個嗎。于是開始測試驗證,結(jié)果發(fā)現(xiàn)的確如此。當(dāng)實例化一個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("我被調(diào)用了");
}
}
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 執(zhí)行結(jié)果如下:
我被調(diào)用了 ===============分割線============= 我被調(diào)用了
原來,在不知不覺中Spring已經(jīng)幫我們做了很多事情,只是我們不知道而已。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
servlet+jsp實現(xiàn)過濾器 防止用戶未登錄訪問
這篇文章主要為大家詳細(xì)介紹了servlet+jsp實現(xiàn)過濾器,防止用戶未登錄訪問,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-04-04
JSP中使用JDBC訪問SQL Server 2008數(shù)據(jù)庫示例
這篇文章主要介紹了JSP中使用JDBC訪問SQL Server 2008數(shù)據(jù)庫示例,本文重點在JSP代碼示例中,需要的朋友可以參考下2014-09-09

