前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring @Autowired 注入到List和Map

Spring @Autowired 注入到List和Map

作者头像
春哥大魔王
发布2019-05-05 10:33:03
12.8K1
发布2019-05-05 10:33:03
举报

前言

我们系统中有一段这样的代码,很多新来的同学看起来比较蒙,这会不会报空指针啊!

其实spring是支持这种基于接口实现类的直接注入的。

实例

BeanInterface只是一个接口无方法。

代码语言:javascript
复制
package com.Autowired.ListMap;  
  
import org.springframework.core.annotation.Order;  
import org.springframework.stereotype.Component;  
/** 
 * order:把实现类排序输出 只适合List 
 * @author liu 
 * 
 */  
@Order(2)  
@Component  
public class BeanImplOne implements BeanInterface {  
  
}  


package com.Autowired.ListMap;  
  
import org.springframework.core.annotation.Order;  
import org.springframework.stereotype.Component;  
  
@Order(1)  
@Component  
public class BeanImplTwo implements BeanInterface {  
  
}  

测试:

代码语言:javascript
复制
package com.Autowired.ListMap;  
  
import java.util.List;  
import java.util.Map;  
  
  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.beans.factory.annotation.Qualifier;  
import org.springframework.stereotype.Component;  
  
@Component  
public class BeanInvoke {  
      
    @Autowired  
      private List<BeanInterface> list;  
        
    @Autowired  
    private Map<String,BeanInterface> map;  
      
    /** @Autowired默认为byType的  所以有两个相同类型的bean   
     * 如果不使用 @Qualifier指定具体的bean就会抛出异常 
     *  private BeanInterface beaninterface; 
     */  
    @Autowired  
   @Qualifier("beanImplOne")  
    private BeanInterface beaninterface;  
    public void say(){  
        System.out.println("list...");  
        if(null !=list &&0!=list.size()){  
            for(BeanInterface bean :list){  
                System.out.println(bean.getClass().getName());  
            }  
              
        }else{  
            System.out.println("List<BeanInterface> list is null !!!!");  
        }  
        System.out.println();  
        System.out.println("map...");  
        if(null !=map &&0!=map.size()){  
            for(Map.Entry<String, BeanInterface> m:map.entrySet()){  
                  System.out.println(m.getKey()+"    "+m.getValue().getClass().getName());  
            }  
        }else{  
            System.out.println("Map<String,BeanInterface> map is null !!!!");  
  
        }  
        System.out.println("-------------------------");  
        if(null !=beaninterface){  
            System.out.println(beaninterface.getClass().getName());  
        }else{  
            System.out.println("beaninterface is null !!!");  
        }  
    }  
      
      
}  


package com.Autowired.ListMap;  
  
import org.junit.Test;  
  
import com.imooc.test.base.UnitTestBase;  
  
  
public class TestListMap  extends UnitTestBase{  
    public TestListMap(){  
        super("classpath*:spring-beanannotation3.xml");  
    }  
      
    @Test  
    public void test(){  
        BeanInvoke  bean=super.getBean("beanInvoke");  
        bean.say();  
    }  
}  

配置文件:

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context  
        http://www.springframework.org/schema/context/spring-context.xsd" >  
          
        <context:component-scan base-package="package com.Autowired.ListMap;"></context:component-scan>  
          
 </beans>  

输出结果:

代码语言:javascript
复制
2017-6-4 15:38:26 org.springframework.context.support.AbstractApplicationContext prepareRefresh  
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@58a17083: startup date [Sun Jun 04 15:38:26 CST 2017]; root of context hierarchy  
2017-6-4 15:38:26 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions  
信息: Loading XML bean definitions from URL [file:/E:/myeclipse/workspace/Spring2/bin/spring-beanannotation3.xml]  
2017-6-4 15:38:27 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>  
信息: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring  
list...  
2017-6-4 15:38:27 org.springframework.context.support.AbstractApplicationContext doClose  
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@58a17083: startup date [Sun Jun 04 15:38:26 CST 2017]; root of context hierarchy  
com.Autowired.ListMap.BeanImplTwo  
com.Autowired.ListMap.BeanImplOne  
  
map...  
beanImplOne    com.Autowired.ListMap.BeanImplOne  
beanImplTwo    com.Autowired.ListMap.BeanImplTwo  
-------------------------  
com.Autowired.ListMap.BeanImplOne  

Spring吧bean放入了List中 那个这个顺序怎么控制呢

在实现类中加入@Order(value) 注解即可 ,值越小越先被初始化越先被放入List

看下源码

代码语言:javascript
复制
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注入了,导致上面的输出结果。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-03-28,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 春哥talk 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 实例
  • 看下源码
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档