詳解 Spring注解的(ListMap)特殊注入功能
最近接手一個(gè)新項(xiàng)目,已經(jīng)沒(méi)有原開發(fā)人員維護(hù)了。項(xiàng)目框架是基于spring boot進(jìn)行開發(fā)。其中有兩處Spring的注解花費(fèi)了大量的時(shí)間才弄明白到底是怎么用的,這也涉及到spring注解的一個(gè)特殊的注入功能。
首先,看到代碼中有直接注入一個(gè)List和一個(gè)Map的。示例代碼如下:
@Autowired
private ListDemoService> demoServices;
@Autowired
private MapString,DemoService> demoServiceMap;
以上是兩處代碼示例化之后的demo。當(dāng)時(shí)看到這里之后有些懵,全局搜索之后并沒(méi)有發(fā)現(xiàn)定義一個(gè)List和Map的對(duì)象。然而debug運(yùn)行之后卻發(fā)現(xiàn)它們的確都有值。這個(gè)事情就有些神奇了。在網(wǎng)上搜索也收獲甚微。
最后在調(diào)試List的時(shí)候突然靈感一閃,如果只有一個(gè)對(duì)象那么List里面的值不就只有一個(gè)嗎。于是開始測(cè)試驗(yàn)證,結(jié)果發(fā)現(xiàn)的確如此。當(dāng)實(shí)例化一個(gè)DemoService之后,另外一個(gè)類采用泛型注入List,Spring竟然成功的將實(shí)例化的對(duì)象放入List之中。思路打開之后,針對(duì)Map的就更好說(shuō)了。Spring會(huì)將service的名字作為key,對(duì)象作為value封裝進(jìn)入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 ListDemoService> demoServices;
@Autowired
private MapString,DemoService> demoServiceMap;
@ResponseBody
@RequestMapping(value = "/test")
public String test(){
for(Map.EntryString,DemoService> entry : demoServiceMap.entrySet()){
entry.getValue().test();
}
System.out.println("===============分割線=============");
for(DemoService demoService : demoServices){
demoService.test();
}
return "success";
}
}
運(yùn)行之后,訪問(wèn)http://localhost:8080/demo/test 執(zhí)行結(jié)果如下:
我被調(diào)用了
===============分割線=============
我被調(diào)用了
原來(lái),在不知不覺(jué)中Spring已經(jīng)幫我們做了很多事情,只是我們不知道而已。
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
您可能感興趣的文章:- spring通過(guò)構(gòu)造函數(shù)注入實(shí)現(xiàn)方法分析
- 詳解Spring 兩種注入的方式(Set和構(gòu)造)實(shí)例
- Spring不能注入Static變量的原因及Spring注入靜態(tài)變量
- 詳解Java Spring各種依賴注入注解的區(qū)別
- Spring 依賴注入的幾種方式詳解
- spring boot 注入 property的三種方式(推薦)
- 詳解Spring中bean的幾種注入方式
- 詳析Spring中依賴注入的三種方式
- spring boot靜態(tài)變量注入配置文件詳解
- 詳解Spring @Autowired 注入小技巧
- 詳解SpringBoot中實(shí)現(xiàn)依賴注入功能
- Spring框架構(gòu)造注入操作實(shí)戰(zhàn)案例