Spring @Autowired 注入到List和Map

前言

咱們系統中有一段這樣的代碼,不少新來的同窗看起來比較蒙,這會不會報空指針啊! java

其實spring是支持這種基於接口實現類的直接注入的。spring

實例

BeanInterface只是一個接口無方法。數組

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 {  
  
}

測試:eclipse

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();  
    }  
}

配置文件:測試

<?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>

輸出結果:spa

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) 註解便可 ,值越小越先被初始化越先被放入Listcode

看下源碼

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注入了,致使上面的輸出結果。component

相關文章
相關標籤/搜索