map injection

This commit is contained in:
mherbaghinyan 2018-05-21 12:15:30 +04:00
parent d73f653eb0
commit 4cdf7fe9ef
3 changed files with 23 additions and 3 deletions

View File

@ -3,9 +3,7 @@ package com.baeldung.collection;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import java.util.Arrays; import java.util.*;
import java.util.HashSet;
import java.util.List;
@Configuration @Configuration
public class CollectionConfig { public class CollectionConfig {
@ -19,4 +17,13 @@ public class CollectionConfig {
public List<String> nameList(){ public List<String> nameList(){
return Arrays.asList("John", "Adam", "Harry", null); return Arrays.asList("John", "Adam", "Harry", null);
} }
@Bean
public Map<Integer, String> nameMap(){
Map<Integer, String> nameMap = new HashMap<>();
nameMap.put(1, "John");
nameMap.put(2, "Adam");
nameMap.put(3, "Harry");
return nameMap;
}
} }

View File

@ -14,5 +14,6 @@ public class CollectionInjectionDemo {
CollectionsBean collectionsBean = context.getBean(CollectionsBean.class); CollectionsBean collectionsBean = context.getBean(CollectionsBean.class);
collectionsBean.printNameList(); collectionsBean.printNameList();
collectionsBean.printNameSet(); collectionsBean.printNameSet();
collectionsBean.printNameMap();
} }
} }

View File

@ -3,6 +3,7 @@ package com.baeldung.collection;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
/** /**
@ -15,6 +16,8 @@ public class CollectionsBean {
private Set<String> nameSet; private Set<String> nameSet;
private Map<Integer, String> nameMap;
public CollectionsBean() { public CollectionsBean() {
} }
@ -22,6 +25,11 @@ public class CollectionsBean {
this.nameSet = strings; this.nameSet = strings;
} }
@Autowired
public void setNameMap(Map<Integer, String> nameMap) {
this.nameMap = nameMap;
}
public void printNameList() { public void printNameList() {
System.out.println(nameList); System.out.println(nameList);
} }
@ -29,4 +37,8 @@ public class CollectionsBean {
public void printNameSet() { public void printNameSet() {
System.out.println(nameSet); System.out.println(nameSet);
} }
public void printNameMap() {
System.out.println(nameMap);
}
} }