본문 바로가기
교재 실습/자바 웹 개발 워크북

140. 컬렉션 값 주입 (1)

by Jint 2022. 10. 25.

자바에서는 배열이나 List와 같이 여러 개의 값을 저장하고 다루는 객체를 컬렉션(collection)이라 부른다. 이번 절에서는 자주 사용하는 컬렉션 타입인 배열, List, Set, Map, Properties의 값을 설정하는 방법을 알아본다.

 

1. 배열 프로퍼티의 값 주입

먼저 빈의 프로퍼티가 배열이나, List, Set 타입인 경우, 어떻게 값을 설정하는지 배워본다.

 

- 실습 패키지 생성

exam 패키지 아래에 test09 패키지를 생성한다. test08 패키지의 모든 파일을 복사해온다.

 

- beans.xml 빈 설정 파일

exam/test09/beans.xml 파일을 열고 다음과 같이 편집한다.

<?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:p="http://www.springframework.org/schema/p"
    xmlns:c="http://www.springframework.org/schema/c"
 	xsi:schemaLocation="http://www.springframework.org/schema/beans
						http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="car1" class="exam.test09.Car">
		<constructor-arg value="Avante"/>
		<constructor-arg>
			<bean class="exam.test09.Engine" p:maker="Hyundai" p:cc="1495"/>
		</constructor-arg>
		<property name="tires">
			<list>
				<bean class="exam.test09.Tire" p:maker="Kumho" p:spec="P185/65R14"/>
				<bean class="exam.test09.Tire" p:maker="Kumho" p:spec="P185/65R14"/>
				<bean class="exam.test09.Tire" p:maker="Hankook" p:spec="P205/65R14"/>
				<bean class="exam.test09.Tire" p:maker="Hankook" p:spec="P205/65R14"/>
			</list>
		</property>
	</bean>

</beans>

 

<property name="tires">
    <list>...</list>
</property>

 

▶ 자바 코드로 표현하면?
Engine temp new Engine();
temp.setMaker("Hyundai");
temp.setCc(1495);
Car car1 = new Car("Avante", temp);
Tire[] temp2 = new Tire[] {new Tire(), new Tire(), new Tire(), new Tire()};
temp2[0].setMaker("Kumho");
temp2[0].setSpec("P185/65R14");
temp2[1].setMaker("Kumho");
temp2[1].setSpec("P185/65R14");
temp2[2].setMaker("Hankook");
temp2[2].setSpec("P205/65R14");
temp2[3].setMaker("Hankook");
temp2[3].setSpec("P205/65R14");
car1.setTire(temp2);

Car 클래스의 tires 프로퍼티는 배열(Tire[])타입이다. 배열이나 java.util.List 타입의 프로퍼티는 값을 설정할 때 <list> 태그를 사용한다. 배열에 들어갈 값은 <list> 태그의 자식 태그로 선언한다.

<list>
    <value>간단한 상수값</value>
    <ref bean="빈 레퍼런스"/>
    <null/>
    <bean class="클래스명(패키지명 포함)"/>
</list>

배열이나 리스트에 간단한 상숫값을 추가할 때는 <value> 태그를 사용한다. 다른 빈의 레퍼런스를 추가할 때는 <ref> 태그를 사용한다. null 값을 넣을 때는 <null> 태그를, 빈을 새로 만들어 넣을 때는 <bean> 태그를 사용한다. 앞의 예제 코드는 'Kumho' 타이어 2개와 'Hankook' 타이어 2개를 새로 만들어 배열에 담고 있다.

<property name="프로퍼티 이름">
    <set>
        <value>간단한 상수값</value>
        <ref bean="빈 레퍼런스"/>
        <null/>
        <bean class="클래스명(패키지명 포함)"/>
    </set>
</property>

java.util.Set 타입도 값을 설정하는 방법은 java.util.List와 같다. 다만 값을 넣을 때 기존에 등록된 객체와 값이 같은지 조사하여 같지 않을 경우에만 Set에 추가한다. 값이 중복되지 않는 것은 집합(Set)의 고유 성질이다.

 

※ equals()와 hashCode()

자바에서 두 객체가 같은지 비교할 때는 두 가지 경우가 있다. 그 중 하나는 인스턴스가 같은지 엄격히 비교하는 경우인데, 이 경우 '==' 연산자를 사용하여 검사한다. 두 변수가 같은 인스턴스를 가리킨다면 변수에 저장된 주소가 같을 것이다.

다른 하나는 두 객체의 내용이 같은지를 비교하는 경우이다. 이 경우에는 equals() 메서드와 hashCode() 메서드를 사용하여 검사한다. equals() 메서드 반환값이 true 이고, hashCode() 메서드의 반환값이 같다면 두 객체가 같은 내용을 갖고 있다고 간주한다.

 

- 빈 컨테이너 테스트

tires 배열 프로퍼티에 값이 잘 들어갔는지 확인해 본다. exam.test09.Test 클래스를 다음과 같이 편집한다.

package exam.test09;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	
	public static void main(String[] args) {
		//IoC 컨테이너 준비하여 빈 생성
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("exam/test09/beans.xml");
		
		Car car1 = (Car)ctx.getBean("car1");
		System.out.println(car1);
		for(Tire tire : car1.getTires()) {
			System.out.println(tire);
		}
	}
	
}

그림 1 (exam.test09.Test 클래스 실행 결과)

빈 컨테이너에서 'car1' 객체를 꺼내어 출력한다. 그리고 tires 배열 프로퍼티에 들어있는 항목을 출력한다. 실행 결과를 보면 <list> 태그에 선언된 대로 타이어 정보를 출력하고 있다.

 

참고도서 : https://freelec.co.kr/book/1674/

 

[열혈강의] 자바 웹 개발 워크북

[열혈강의] 자바 웹 개발 워크북

freelec.co.kr

댓글