Spring Dependency Injection 简明教程
Spring DI - Map Setter
您已经看到如何使用 Bean 配置文件中的 <property> 标记的 value 属性配置原始数据类型,以及使用 ref 属性配置对象引用。这两种情况都涉及将奇异值传递给 Bean。
You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean.
现在,如果你想传递 Map,该怎么办?在本示例中,我们展示使用 setter 注入传递 Map 的直接值。
Now what if you want to pass Map. In this example, we’re showcasing passing direct values of the Map using setter injection.
Example
以下示例展示了一个类 JavaCollection,该类使用集合作为依赖关系,并使用 setter 方法进行注入。
The following example shows a class JavaCollection that is using collections as dependency injected using setter method.
让我们更新在 Spring DI - Create Project 章节中创建的项目。我们将添加以下文件 −
Let’s update the project created in Spring DI - Create Project chapter. We’re adding following files −
-
JavaCollection.java − A class containing a collections as dependency.
-
MainApp.java − Main application to run and test.
以下是 JavaCollection.java 文件的内容−
Here is the content of JavaCollection.java file −
package com.tutorialspoint;
import java.util.*;
public class JavaCollection {
Map<String, String> addressMap;
public JavaCollection() {}
public JavaCollection(Map<String, String> addressMap) {
this.addressMap = addressMap;
}
// a setter method to set Map
public void setAddressMap(Map<String, String> addressMap) {
this.addressMap = addressMap;
}
// prints and returns all the elements of the Map.
public Map<String, String> getAddressMap() {
System.out.println("Map Elements :" + addressMap);
return addressMap;
}
}
以下是 MainApp.java 文件的内容−
Following is the content of the MainApp.java file −
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
JavaCollection jc=(JavaCollection)context.getBean("javaCollection");
jc.getAddressMap();
}
}
以下是配置文件 applicationcontext.xml ,其中包含了所有类型的集合配置 −
Following is the configuration file applicationcontext.xml which has configuration for all the type of collections −
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "javaCollection" class = "com.tutorialspoint.JavaCollection">
<property name = "addressMap">
<map>
<entry key = "1" value = "INDIA"/>
<entry key = "2" value = "JAPAN"/>
<entry key = "3" value = "USA"/>
<entry key = "4" value = "UK"/>
</map>
</property>
</bean>
</beans>