교재 실습/자바 웹 개발 워크북

145. 날짜 값 주입 (1)

Jint 2022. 11. 7. 23:25

이번 절에서는 java.util.Date 타입의 프로퍼티 값을 설정하는 방법을 배운다. 스프링에서는 빈의 프로퍼티에 값을 설정할 때 태그의 컨텐츠(시작 태그와 끝 태그 사이의 값)나 태그의 속성(시작 태그 안에 작성하는 속성의 값)을 사용한다.

그림 1 (프로퍼티 값 설정)

빈 설정 파일은 XML이기 때문에 결국 프로퍼티의 값은 문자열로 표현한다(그림 1). 문자열은 숫자로 변환하기 쉽기 때문에 숫자 타입 프로퍼티인 경우 별도의 추가 작업없이 간단히 값을 설정할 수 있다. 하지만, 그 외 타입은 자동으로 변환되지 않는다. 개발자가 프로퍼티 타입에 맞는 객체를 생성해야 한다. 다음 실습은 개발자가 직접 java.util.Date 타입의 프로퍼티 값을 설정하는 예이다.

 

1. SimpleDateFormat 클래스와 인스턴스 팩토리 메서드 활용

SimpleDateFormat 클래스와 팩토리 메서드 방식을 활용하여 날짜 값을 설정해본다. 다음 그림은 SimpleDateFormat 클래스의 parse() 메서드를 팩토리 메서드로 활용하여 java.util.Date 객체를 얻는 것을 표현한 것이다(그림 2).

그림 2 (SimpleDateFormat 객체로 날짜 값 설정)

 

- 실습 패키지 생성

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

 

- beans.xml 빈 설정 파일

exam/test15/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="dateFormat" class="java.text.SimpleDateFormat">
		<constructor-arg value="yyyy-MM-dd"/>
	</bean>

	<bean id="hankookTire" class="exam.test15.Tire">
		<property name="maker" value="Hankook"/>
		<property name="createdDate">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2014-5-5"/>
			</bean>
		</property>
	</bean>
	
	<bean id="kumhoTire" class="exam.test15.Tire">
    	<property name="maker" value="Kumho"/>
    	<property name="createdDate">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2014-1-14"/>
			</bean>
		</property>
	</bean>

</beans>

 

<bean id="dateFormat" class="java.text.SimpleDateFormat">
    <constructor-arg value="yyyy-MM-dd"/>
</bean>

 

▶ 자바 코드로 표현하면?
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

SimpleDateFormat 객체는 날짜 형식의 문자열을 java.util.Date 객체로 변환해 준다. 생성자 매개변수 값으로 날짜 형식을 지정한다. yyyy는 4자리로 이루어진 년도(예 : 2014)이다. MM은 월(예 : 05 또는 5)이다. dd는 해당 월의 일자(예 : 05 또는 5)이다. 즉 2014-5-5 형식의 문자열을 java.util.Date 객체로 만들어 준다.

<property name="createdDate">
    ...
</property>

'hankookTire' 객체의 createdDate는 java.util.Date 타입의 프로퍼티이다. 이 프로퍼티에 넣을 수 있는 값은 날짜 객체이다.

<property name="createdDate">
    <bean factory-bean="dateFormat" factory-method="parse">
        ...
    </bean>
</property>

날짜 객체를 얻기 위해 팩토리 메서드를 선언한다. factory-bean 속성에는 앞에서 정의한 SimpleDateFormat 객체를 지정하고, factory-method 속성에는 parse() 메서드를 지정한다. parse() 메서드는 문자열을 가지고 날짜 객체를 만들어주는 인스턴스 메서드이다.

<property name="createdDate">
    <bean factory-bean="dateFormat" factory-method="parse">
        <constructor-arg value="2014-5-5"/>
    </bean>
</property>

 

▶ 자바 코드로 표현하면?
hankookTire.setCreatedDate(dateFormat.parse("2014-5-5"));

끝으로 <constructor-arg> 태그를 사용하여 parse() 메서드에 넘겨줄 날짜 형식의 문자열을 지정한다. 'kumhoTire' 설정도 제조일(2014-1-14)만 빼고 'hankookTire'와 같다.

 

- 빈 컨테이너 테스트

createdDate 프로퍼티에 설정한 날짜 값이 정확히 들어갔는지 확인해 본다. test14 패키지에서 복사해 온 테스트 클래스 exam.test15.Test 클래스를 다음과 같이 편집한다.

package exam.test15;

import java.text.SimpleDateFormat;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	
	public static void main(String[] args) {
		//IoC 컨테이너 준비하여 빈 생성
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("exam/test15/beans.xml");
		
		System.out.println("[인스턴스 팩터리 메서드 활용]-------------------------");

		SimpleDateFormat dateFormat = (SimpleDateFormat)ctx.getBean("dateFormat");
		
		Tire hankookTire = (Tire)ctx.getBean("hankookTire");
		System.out.println(hankookTire.getMaker());
		System.out.println(dateFormat.format(hankookTire.getCreatedDate()));
		
		System.out.println("------------------------------");
		
		Tire kumhoTire = (Tire)ctx.getBean("kumhoTire");
		System.out.println(kumhoTire.getMaker());
		System.out.println(dateFormat.format(kumhoTire.getCreatedDate()));
	}
	
}

 

SimpleDateFormat dateFormat = (SimpleDateFormat)ctx.getBean("dateFormat");

빈 컨테이너에서 'dateFormat' 객체를 꺼낸다. 화면에 yyyy-MM-dd 형식으로 출력하기 위해서 이다.

Tire hankookTire = (Tire)ctx.getBean("hankookTire");
System.out.println(hankookTire.getMaker());
System.out.println(dateFormat.format(hankookTire.getCreatedDate()));

그림 3 (exam.test15.Test 클래스 실행 결과)

getBean() 메서드를 호출하여 'hankookTire' 객체를 꺼낸다. 타이어 객체(hankookTire)에 대해 getCreatedDate() 메서드를 호출하여 날짜 객체를 꺼낸다. SimpleDateFormat 객체의 format() 메서드를 이용하여 날짜 객체를 '년-월-일' 형식으로 출력한다. 출력 결과를 보면 'hankookTire'와 'kumhoTire' 모두 프로퍼티에 설정한 값이 그대로 출력되는 것을 알 수 있다.

 

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

 

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

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

freelec.co.kr