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已经帮我们做了很多事情,只是我们不知道而已。

原文地址:https://www.cnblogs.com/tonysengj/p/10401691.html