Spring – 05 – Injection – Collection Injection

Merhaba Arkadaslar
Onceki bolumde Setter Injection ve Constructor Injection konularini inceledik. Burada kullandigimiz orneklerde property’lerimiz String , int gibi tipler oldu. Peki soz konusu Collection oldugunda injection islemini nasil gerceklestirecegiz ? Inceleyelim..

  • Collection Injection with XML
  • Collection Injection with Annotation

Collection Injection with XML

Spring bizim icin <list> , <map> , <set> ve <props> tag’larini saglar. Oncelikle <list> tagini inceleyelim.

CollectionInjection.java

public class CollectionInjection {

     private List<String> myList;
     private List<Person> personList;
     private Set<Integer> mySet;
     private Map<String, Object> myMap;
     private Properties myProperties;
     //getters and setters
...
}

List<String> tipindeki myList propery’mize <list> ve <value> tagini kullanarak eleman ekleyebiliriz.

05.collection.injection.xml

	....
        <bean id="collectionId" class="_05.collection.injection.model.CollectionInjection">
		<property name="myList">
			<list>
				<value>list element1</value>
				<value>list element2</value>
				<value>list element3</value>
				<value>list element4</value>
			</list>
		</property> 
	</bean>
...

Benzer sekilde List<Person> tipindeki personList property’imize <list> ve <ref> tagini kullanarak eleman ekleyebiliriz  ya da <bean> tagini kullanarak yeni bean olusturup ekleyebiliriz.

	<bean id="collectionId" class="_05.collection.injection.model.CollectionInjection">
		<property name="myList">
			<list>
				<value>list element1</value>
				<value>list element2</value>
				<value>list element3</value>
				<value>list element4</value>
			</list>
		</property>

		<property name="personList">
			<list>
				<ref bean="personId1" />

				<bean id="personId2" class="_05.collection.injection.model.Person">
					<property name="name" value="test name2" />
					<property name="surname" value="test surname2" />
				</bean>

				<bean id="personId3" class="_05.collection.injection.model.Person">
					<property name="name" value="test name3" />
					<property name="surname" value="test surname3" />
				</bean>

				<bean id="personId4" class="_05.collection.injection.model.Person">
					<property name="name" value="test name4" />
					<property name="surname" value="test surname4" />
				</bean>

			</list>
		</property>
	</bean>


	<bean id="personId1" class="_05.collection.injection.model.Person">
		<property name="name" value="test name" />
		<property name="surname" value="test surname" />
	</bean>

<list> tagina benzer sekilde <set> tagini kullanabiliriz. Hatirlayacagimiz gibi Set yapisinda duplicate elemana izin verilmez.

	<bean id="collectionId" class="_05.collection.injection.model.CollectionInjection">
....
		<property name="mySet">
			<set>
				<value>10</value>
				<value>10</value>
				<value>20</value>
				<value>20</value>
				<value>30</value>
				<value>40</value>
				<value>50</value>
			</set>
		</property>
...
	</bean>

<map> tag’inda <entry> tagi ile key/value cifti ekleyebiliriz. <entry> tag’i icerisinde <value> tagi kullanabiliriz ya da value attribute kullanabiliriz. value-ref attribute kullanarak bean id verebiliriz.

<property name="myMap">
	<map>
		<entry key="key1">
			<value>value1</value>
		</entry>
		<entry key="key2">
			<value>value2</value>
		</entry>
		<entry key="key3" value="value3" />
		<entry key="key4">
			<bean id="personId1" class="_05.collection.injection.model.Person">
				<property name="name" value="map name" />
				<property name="surname" value="map surname" />
			</bean>
		</entry>
		<entry key="key5">
			<ref bean="personId1"/>
		</entry>
		<entry key="key6" value-ref="personId1" />
	</map>
</property>

<props> ve <prop> tag’larini kullanalim ;

<property name="myProperties">
 <props>
    <prop key="prop1">propvalue1</prop>
    <prop key="prop2">propvalue2</prop>
    <prop key="prop3">propvalue3</prop>
    <prop key="prop4">propvalue4</prop>
    <prop key="prop5">propvalue5</prop>
 </props>
</property>

List , Set , Map ve Properties degerlerini yazdiralim ;

CollectionInjectionTest.java

package _05.collection.injection.test;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import _05.collection.injection.model.CollectionInjection;
import _05.collection.injection.model.Person;

public class CollectionInjectionTest {

	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("05.collection.injection.xml");

		CollectionInjection collectionInjection = ctx.getBean("collectionId", CollectionInjection.class);

		List<String> myList = collectionInjection.getMyList();
		List<Person> myPerson = collectionInjection.getPersonList();
		Set<Integer> mySet = collectionInjection.getMySet();
		Map<String, Object> myMap = collectionInjection.getMyMap();
		Properties myProperties = collectionInjection.getMyProperties();

		System.out.println("myList elements : ");
		// for (String element : myList) {
		// System.out.println(element);
		// }

		// java8
		myList.stream().forEach(System.out::println);

		System.out.println("myPerson elements : ");
		// for (Person element : myPerson) {
		// System.out.println(element);
		// }

		// java8
		myPerson.stream().forEach(System.out::println);

		System.out.println("mySet elements : ");
		// for (Integer element : mySet) {
		// System.out.println(element);
		// }

		// java8
		mySet.forEach(System.out::println);

		System.out.println("myMap elements : ");
		// for (Object element : myMap.keySet()) {
		// System.out.println(myMap.get(element));
		// }

		// java8
		myMap.forEach((k, v) -> System.out.println("key : " + k + " value : " + v));

		System.out.println("myProperties elements : ");
		// for (Map.Entry<Object, Object> entry : myProperties.entrySet()) {
		// System.out.println(entry.getKey() + " " + entry.getValue());
		// }

		// java8
		myProperties.forEach((k, v) -> System.out.println("key : " + k + " value : " + v));

		((ClassPathXmlApplicationContext) ctx).close();
	}
}

Ornegimizi calistirdigimizda

myList elements : 
list element1
list element2
list element3
list element4
myPerson elements : 
Person [name=test name, surname=test surname]
Person [name=test name2, surname=test surname2]
Person [name=test name3, surname=test surname3]
Person [name=test name4, surname=test surname4]
mySet elements : 
10
20
30
40
50
myMap elements : 
key : key1 value : value1
key : key2 value : value2
key : key3 value : value3
key : key4 value : Person [name=map name, surname=map surname]
key : key5 value : Person [name=test name, surname=test surname]
key : key6 value : Person [name=test name, surname=test surname]
myProperties elements : 
key : prop1 value : propvalue1
key : prop2 value : propvalue2
key : prop3 value : propvalue3
key : prop4 value : propvalue4
key : prop5 value : propvalue5

Collection Injection with Annotation

Collection’lari annotation ile de kullanabiliriz. Bunun icin XML dosyamizda <util:list> , <util:set> , <util:map> , <util:properties> tag’larindan yararlanabiliriz.

05.collection.injection.annotation.xml

Ornegimizi inceleyecek olursak dosyamizin basinda <util:…> taglarini kullanabilmek icin xsi:schemaLocation ve xlmns tanimi ekledik. Yine benzer sekilde <context : component – scan> tagi icin tanimlamalar ekledik. Bunun disinda yukaridaki ornegimize benzer sekilde <util:list> , <util:set> , <util:map> , <util:properties> taglarini kullaniyoruz.

<?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"
	xmlns:util="http://www.springframework.org/schema/util"
	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
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">


	<context:component-scan base-package="_05.collection.injection.model"></context:component-scan>

	<util:list id="myAnnotationList">
		<value>test list1</value>
		<value>test list2</value>
	</util:list>

	<util:list id="myAnnotationPersonList">
		<ref bean="personId1" />
		<bean id="personId2" class="_05.collection.injection.model.Person">
			<property name="name" value="test name2" />
			<property name="surname" value="test surname2" />
		</bean>

		<bean id="personId3" class="_05.collection.injection.model.Person">
			<property name="name" value="test name3" />
			<property name="surname" value="test surname3" />
		</bean>

		<bean id="personId4" class="_05.collection.injection.model.Person">
			<property name="name" value="test name4" />
			<property name="surname" value="test surname4" />
		</bean>

	</util:list>

	<util:set id="myAnnotationSet">
		<value type="int">10</value>
		<value type="int">20</value>
	</util:set>


	<util:map id="myAnnotationMap">
		<entry key="key1">
			<value>value1</value>
		</entry>

		<entry key="key2">
			<value>value2</value>
		</entry>
	</util:map>

	<util:properties id="myAnnotationProperties">
		<prop key="propkey">propvalue</prop>
		<prop key="propkey2">propvalue2</prop>
	</util:properties>

	<bean id="personId1" class="_05.collection.injection.model.Person">
		<property name="name" value="test name" />
		<property name="surname" value="test surname" />
	</bean>

</beans>

Yeni bir sinif tanimlayalim <context : component – scan>  tag’inin isini yapmasi icin @Service annotation ve tanimladigimiz kaynaklari/resource inject etmek icin @Resource annotation kullaniyoruz. XML dosyamizdaki ilgili isimlerle ayni olacak sekilde isim verdigimize dikkat edelim.

<context:component-scan> etiketi , @Component , @Controller , @Repository ya da @Service annotation’a sahip bean’leri ilgili package’ta aramasini Spring’e soyler ve @Autowired , @Inject annotation ile Dependency Injection’i yapmasini belirtir.

<context:component-scan> etiketi ile birden fazla package’ta da arama yapilabilir bunun icin araya bosluk , virgul ya da noktali virgul koyulabilir.

NOT : Collection type injection soz konusu oldugunda @Autowired yerine @Resource annotation ‘ini kullanmamiz gerekmektedir.
@Resource annotation’ini JSR 250: Common Annotations for the Java da yer almaktadir.

for collection type injection, we have to explicitly instruct Spring to 
perform injection by specifying the bean name, which the @Resource annotation supports

@Value annotation’ini da kullanabiliriz , @Value annotation’da Spring Expression Language kullanabiliriz.
Bir sonraki bolumde Spring Expression Language’i inceleyecegiz.
<context-component-scan> etiketine ve Autowired konusuna ilerleyen bolumlerde deginecegiz.

CollectionInjectionAnnotation.java

package _05.collection.injection.model;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

@Service("collectionInjectionAnnotation")
public class CollectionInjectionAnnotation {

	//@Resource(name="myAnnotationList")
        @Value(value="#{myAnnotationList}")
	private List<String> myList;
	
	@Resource(name="myAnnotationPersonList")
	private List<Person> personList;
	
	@Resource(name="myAnnotationSet")
	private Set<Integer> mySet;
	
	@Resource(name="myAnnotationMap")
	private Map<String, Object> myMap;
	
	@Resource(name="myAnnotationProperties")
	private Properties myProperties;
       //getters and setters
....
...
}

CollectionInjectionAnnotationTest.java

package _05.collection.injection.test;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import _05.collection.injection.model.CollectionInjectionAnnotation;
import _05.collection.injection.model.Person;

public class CollectionInjectionAnnotationTest {

	public static void main(String[] args) {

		ApplicationContext ctx = new ClassPathXmlApplicationContext("05.collection.injection.annotation.xml");

		CollectionInjectionAnnotation collectionInjection = ctx.getBean("collectionInjectionAnnotation",
				CollectionInjectionAnnotation.class);

		List<String> myList = collectionInjection.getMyList();
		List<Person> myPerson = collectionInjection.getPersonList();
		Set<Integer> mySet = collectionInjection.getMySet();
		Map<String, Object> myMap = collectionInjection.getMyMap();
		Properties myProperties = collectionInjection.getMyProperties();

		System.out.println("myList elements : ");
		// for (String element : myList) {
		// System.out.println(element);
		// }

		// java8
		myList.stream().forEach(System.out::println);

		System.out.println("myPerson elements : ");
		// for (Person element : myPerson) {
		// System.out.println(element);
		// }

		// java8
		myPerson.stream().forEach(System.out::println);

		System.out.println("mySet elements : ");
		// for (Integer element : mySet) {
		// System.out.println(element);
		// }

		// java8
		mySet.forEach(System.out::println);

		System.out.println("myMap elements : ");
		// for (Object element : myMap.keySet()) {
		// System.out.println(myMap.get(element));
		// }

		// java8
		myMap.forEach((k, v) -> System.out.println("key : " + k + " value : " + v));

		System.out.println("myProperties elements : ");
		// for (Map.Entry<Object, Object> entry : myProperties.entrySet()) {
		// System.out.println(entry.getKey() + " " + entry.getValue());
		// }

		// java8
		myProperties.forEach((k, v) -> System.out.println("key : " + k + " value : " + v));

		((ClassPathXmlApplicationContext) ctx).close();
	}
}

Ornegimizi calistirdigimizda ;

myList elements : 
test list1
test list2
myPerson elements : 
Person [name=test name, surname=test surname]
Person [name=test name2, surname=test surname2]
Person [name=test name3, surname=test surname3]
Person [name=test name4, surname=test surname4]
mySet elements : 
10
20
myMap elements : 
key : key1 value : value1
key : key2 value : value2
myProperties elements : 
key : propkey value : propvalue
key : propkey2 value : propvalue2

Github kaynak dosyalar/ source folder
leventerguder/injavawetrust-spring-tutorial

Yazimi burada sonlandiriyorum.
Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
OCP, Java SE 6 Programmer
OCE, Java EE 6 Web Component Developer

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *