在Spring中注入列表,集合或者映射

时间:2020-01-09 10:44:29  来源:igfitidea点击:

当我们使用value或者ref属性在Spring中注入依赖项时,可以设置单个原始值或者单个引用的bean。如果我们想在Spring中将值集合作为bean依赖项注入,那该Spring框架提供了一个选项来注入诸如List,Set,Map之类的集合。

在Spring注入集合

在Spring框架中,<list />,<set />,<map />和<props />元素分别设置Java集合类型List,Set,Map和Properties的属性和参数。

<list />:此元素用于连接Spring中的值列表。允许重复并维持订单。这个元素也可以用来连接任何类型的java.util.Collection和一个数组。

<set />:此元素与<list />相似,因为它可以连接值列表,也可以用于连接任何类型的java.util.Collection和数组。使用此元素,不允许重复且不维护顺序。

<map />:此元素用于在Spring中注入(键,值)对的集合,该元素的键和值可以是任何类型。

<props />:此元素用于在Spring中注入(键,值)对的集合,但限制为键和值均为字符串。

在Spring中注入列表和设置示例

本示例说明如何在Spring中注入列表或者集合依赖项。在以下类中,有一个类型为java.util.List的字段cityList和一个类型为java.util.Set的字段citySet。

public class WireCollection {
  //inject a List
  private List<String> cityList;
  //inject a Set
  private Set<String> citySet;
  public List<String> getCityList() {
    return cityList;
  }
  public void setCityList(List<String> cityList) {
    this.cityList = cityList;
  }
  public Set<String> getCitySet() {
    return citySet;
  }
  public void setCitySet(Set<String> citySet) {
    this.citySet = citySet;
  }  
}

组态

<?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">
    
  <bean id="cityBean" class="com.theitroad.springproject.service.WireCollection">
    <property name="cityList">
      <list>
        <value>Tokyo</value>
        <value>Tel Aviv</value>
        <value>Lisbon</value>
        <value>Stockholm</value>
        <value>Stockholm</value>
      </list>
    </property>
    <property name="citySet">
      <set>
        <value>Tokyo</value>
        <value>Tel Aviv</value>
        <value>Lisbon</value>
        <value>Stockholm</value>
        <value>Stockholm</value>
      </set>            
    </property>
  </bean>
</beans>

具有用于运行示例的main方法的类。

public class App {
  public static void main( String[] args ){
    // create context using configuration
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
    WireCollection wc =  context.getBean("cityBean", WireCollection.class);
    System.out.println("*** Cities from city list ***");
    // access the city list
    List<String> cityList =  wc.getCityList();
    for(String city : cityList) {
      System.out.println(city);
    }
    System.out.println("*** Cities from city set ***");
    // access the city set   	
    Set<String> citySet =  wc.getCitySet();
    for(String city : citySet) {
      System.out.println(city);
    }
    // close the context
    context.close();
  }
}

输出:

*** Cities from city list ***
Tokyo
Tel Aviv
Lisbon
Stockholm
Stockholm
*** Cities from city set ***
Tokyo
Tel Aviv
Lisbon
Stockholm

如我们所见,集合中的重复值被拒绝。

在Spring示例中注入地图和道具

public class WireCollection {
  //inject a Map
  private Map<String,Double> cities;
  //inject Properties
  private Properties cityProp;
  public Map<String, Double> getCities() {
    return cities;
  }
  public void setCities(Map<String, Double> cities) {
    this.cities = cities;
  }
  public Properties getCityProp() {
    return cityProp;
  }
  public void setCityProp(Properties cityProp) {
    this.cityProp = cityProp;
  }
}

组态

<?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">
    
  <bean id="cityBean" class="com.theitroad.springproject.service.WireCollection">
    <property name="cities">
      <map>
        <entry key="Tokyo" value="30.5" />
        <entry key="Lisbon" value="28.3" />
        <entry key="Stockholm" value="23.7" />
      </map>
    </property>
    <property name="cityProp">
      <props>
        <prop key="Tokyo">30.5</prop>
        <prop key="Lisbon">28.3</prop>
        <prop key="Stockholm">23.7</prop>
      </props>            
    </property>
  </bean>
</beans>

具有用于运行示例的main方法的类。

public class App {
  public static void main( String[] args ){
    // create context using configuration
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
    WireCollection wc =  context.getBean("cityBean", WireCollection.class);
    System.out.println("*** Cities from city Map ***");
    Map<String,Double> cityMap =  wc.getCities();
    for(Map.Entry<String,Double> city : cityMap.entrySet()) {
      System.out.println("In " + city.getKey() + " temperature is " + city.getValue());
    }
    System.out.println("*** Cities from city Props ***");	
    Properties cityProp =  wc.getCityProp();
    System.out.println(cityProp);
    // close the context
    context.close();
  }
}

输出:

*** Cities from city Map ***
In Tokyo temperature is 30.5
In Lisbon temperature is 28.3
In Stockholm temperature is 23.7
*** Cities from city Props ***
{Tokyo=30.5, Lisbon=28.3, Stockholm=23.7}

在列表,集合,映射中注入bean参考

我们还可以注入一个包含另一个bean引用的集合。在此示例中,有一个名为City的bean,类型为City的list,set和Map store对象。

public class City {
  private String cityName;
  private double avgTemp;
  public String getCityName() {
    return cityName;
  }
  public void setCityName(String cityName) {
    this.cityName = cityName;
  }
  public double getAvgTemp() {
    return avgTemp;
  }
  public void setAvgTemp(double avgTemp) {
    this.avgTemp = avgTemp;
  }	
}
public class WireCollection {
  private List<City> cityList;
  private Set<City> citySet;
  private Map<String,City> cities;
  public List<City> getCityList() {
    return cityList;
  }
  public void setCityList(List<City> cityList) {
    this.cityList = cityList;
  }
  public Set<City> getCitySet() {
    return citySet;
  }
  public void setCitySet(Set<City> citySet) {
    this.citySet = citySet;
  }
  public Map<String, City> getCities() {
    return cities;
  }
  public void setCities(Map<String, City> cities) {
    this.cities = cities;
  }
}

组态

<?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">
    
  <bean id="cityBean" class="com.theitroad.springproject.model.City">
    <property name="cityName" value = "Mumbai" />
    <property name="avgTemp" value = "32.5" />
  </bean>
  <bean id="collectionBean" class="com.theitroad.springproject.service.WireCollection">
    <property name="cityList">
      <list>
        <ref bean="cityBean" />
        <bean class="com.theitroad.springproject.model.City">
          <property name="cityName" value = "Chicago" />
          <property name="avgTemp" value = "15.2" />
        </bean>
      </list>
    </property>
    <property name="citySet">
      <set>
        <ref bean="cityBean" />
        <bean class="com.theitroad.springproject.model.City">
          <property name="cityName" value = "Chicago" />
          <property name="avgTemp" value = "15.2" />
        </bean>
      </set> 
    </property>
    <property name="cities">
      <map>
        <entry key="BOM" value-ref="cityBean" />
        <entry key="CHI">
          <bean class="com.theitroad.springproject.model.City">
            <property name="cityName" value = "Chicago" />
            <property name="avgTemp" value = "15.2" />
          </bean>
        </entry>
      </map>
    </property>
  </bean>
</beans>

在配置中,我们可以看到在所有集合List,Set或者Map Bean中都被引用,并且还作为内部Bean注入,因此有两个选项可用于在集合中设置Bean。当将bean引用为Map的键或者值时,则使用key-ref或者value-ref属性代替键或者值。

具有用于运行示例的main方法的类。

public class App {
  public static void main( String[] args ){
    // create context using configuration
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
    WireCollection wc =  context.getBean("collectionBean", WireCollection.class);
    System.out.println("*** Cities from city list ***");
    // access the city list
    List<City> cityList =  wc.getCityList();
    for(City city : cityList) {
      System.out.println("City: " + city.getCityName() + " Avg. Temp.: " + city.getAvgTemp());
    }
    	
    System.out.println("*** Cities from city set ***");
    // access the city set   	
    Set<City> citySet =  wc.getCitySet();
    for(City city : citySet) {
      System.out.println("City: " + city.getCityName() + " Avg. Temp.: " + city.getAvgTemp());
    }    	
    System.out.println("*** Cities from city Map ***");
    Map<String,City> cityMap = wc.getCities();
    for(Map.Entry<String,City> city : cityMap.entrySet()) {
      System.out.println("In " + city.getValue().getCityName() + " avg. temperature is " + city.getValue().getAvgTemp());
    }
    // close the context
    context.close();
  }
}

输出:

*** Cities from city list ***
City: Mumbai Avg. Temp.: 32.5
City: Chicago Avg. Temp.: 15.2
*** Cities from city set ***
City: Mumbai Avg. Temp.: 32.5
City: Chicago Avg. Temp.: 15.2
*** Cities from city Map ***
In Mumbai avg. temperature is 32.5
In Chicago avg. temperature is 15.2