Spring注解的(List&Map)特殊注入功能

今天偶然在网页留言上发现,有人说用@Autowired

可以注入bean到声明的map中,当时我还不信,怎么可能呢,@Autowired只用过向定义的类型中注入bean,map跟bean非亲非故,怎么会注入那些实例,于是试验了一下,果然灵验

@Autowired
private Map<String, BizService> map = new HashMap<>();//  向map中注入所有类型为BizService类型的bean,其中键为bean的名称,值为bean的实例.

像上面这些注入一个map,类型必须是这样: Map<String, T> map ,即: 键必须是String类型, 值可以是任意类型

这样的话,这个map就会将context中所有类型为T的bean都注入到这个map中了.

分析一下原理,也是很容易实现的,只不过以前没朝这方面想而已

在context启动过程中, 会加载所有的bean到bean工厂中,如果发现有用@Autowired标记的Map类型,那就注入

注入的时候,看map的值类型,然后遍历所有的bean,根据类型放进去就行了.

有了这个东西,以后遇到自定义的bean,都可以自动放入单独的map中,随时供自己调用和处理了,很是方便.

同理: List也可以根据bean的类型自动注入.原理同map.
=============补充=================

使用基于JSX-RS规范的@Inject注解不能注入,原因尚未探索.

一、先看一个示例演示:spring注解的一个特殊的注入功能。

首先,是定义一个接口,3个实现类。

public interface GreetService {

    public String sayHello(String name);
    
}
@Service("china")
public class ChinaGreetServiceImpl implements GreetService {

    @Override
    public String sayHello(String name) {
        return "你好";
    }

}
@Service("japan")
public class JapanGreetServiceImpl implements GreetService {

    @Override
    public String sayHello(String name) {
        return "亚麻得";
    }

}
@Service("usa")
public class UsaGreetServiceImpl2 implements GreetService {

    @Override
    public String sayHello(String name) {
        return "hello";
    }

}

下面看到代码中有直接注入一个List和一个Map的。示例代码如下:

GreetController代码:

@RestController
@RequestMapping("/greet")
public class GreetController {

    @Autowired
    private List<GreetService> greetServiceList;

    @Autowired
    private Map<String, GreetService> greetServiceMap;

    @RequestMapping(value = "/test/{id}", method = RequestMethod.GET)
    public String getbook5(@ApiParam("id编号") @PathVariable("id") Long id) {
        for (Map.Entry<String, GreetService> entry : greetServiceMap.entrySet()) {
            System.out.println(entry.getValue().sayHello("" + id));
        }
        System.out.println("==list====");
        for (GreetService greetService : greetServiceList) {
            System.out.println(greetService.sayHello("" + id));
        }

        return "" + id;
    }

}

最后在调试List的时候突然灵感一闪,如果只有一个对象那么List里面的值不就只有一个吗。于是开始测试验证,结果发现的确如此。当实例化一个GreetController之后,另外一个类采用泛型注入List,Spring竟然成功的将实例化的对象放入List之中。思路打开之后,针对Map的就更好说了。Spring会将service的名字作为key,对象作为value封装进入Map。

运行之后,访问http://127.0.0.1:8091/greet/test/1执行结果如下:

原来,在不知不觉中Spring已经帮我们做了很多事情,只是我们不知道而已。

 二、@Autowired 注入集合类型

从spring-beans-4.3.14.RELEASE.jar的源码可以看看到如下:

在org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DependencyDescriptor, String, Set<String>, TypeConverter) 方法中发现了原因。

对于@Autowired声明的数组、集合类型,spring并不是根据beanName去找容器中对应的bean,而是把容器中所有类型与集合(数组)中元素类型相同的bean构造出一个对应集合,注入到目标bean中。对应到上问配置文件中,就是把容器中所有类型为java.lang.String的bean放到新建的Set中,然后注入到Manager bean中。也就是把resourcePackage和resourceLoaction这两个String注入了,导致上面的输出结果。

在spring reference中也发现相关说明。

@Autowired

If you intend to express annotation-driven injection by name, do not primarily use @Autowired, even if is technically capable of referring to a bean name through @Qualifier values. Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.
As a specific consequence of this semantic difference, beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection or map bean by unique name.
@Autowired applies to fields, constructors, and multi-argument methods, allowing for narrowing through qualifier annotations at the parameter level. By contrast, @Resource is supported only for fields and bean property setter methods with a single argument. As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.

从上面的说明中找到解决办法就是注入集合类型不要使用@Autowired,而使用@Resource注解。同时Spring官方也是不推荐使用@Autowired的。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值