'spring3.0'에 해당되는 글 1건

  1. 2012.05.14 Spring3.0 message&event 1

Spring3.0 message&event

2012. 5. 14. 19:07

메시지 및 이벤트 처리 - 국제화


==================================이론======================================

*메시지 소스를 이용한 메시지 국제화 처리

* 프로퍼티 파일은 유니코드를 이용하여 값을 표시해 주어야 한다. (JDK에서 제공하는 native2ascii를 이용하여 유니코드 값으로 변환)

<!-- 국제화 처리를 위한 리소스 번들지정  -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>message.greeting</value>
            <value>message.error</value>
        </list>       
    </property>
</bean>

* 빈 객체에서 메시지 이용하기

 - ApplicationContextAware 인터페이스를 구현한 뒤, setApplicationContext()메서드를 통해 전달받은 ApplicationContext의 getMessage()메서드를 이용하여 메시지 사용
 - MessageSourceAware 인터페이스 구현한 뒤, setMessageSource() 메서드를 통해 전달받은 MessageSource의 getMessage()메서드를  이용하여 메시지 사용


public interface MessageSourceAware{
    void setMessageSource(MessageSource messageSource)
}

public class LogingProcessor implements MessageSourceAware{

   private MessageSource messageSource;

   public void setMessageSource(MessageSource messageSource){
       this.messageSource = messageSource;
   }

   public void login(String username, String password){
        ...
        Object[] arg = new String[] {username};
        String failMessage = messageSource.getMessage("login.fail",args,locale);
        ...
   }
}


*스프링 컨텍스트 이벤트

ApplicationContext는 이벤트를 발생시킬수 있는 publishEvent() 메서드를 제공한다.

void publishEvent(ApplicationEvent event)

publishEvent() 메서드는 org.springframework.context.ApplicationEvent 타입의 객를 전달 받는다.

ApplicationEvent 는 추상 클래스로서 다음과 같이 생성자를 통해서 이벤트를 발생시킨 객체를 전달받는다.

public abstract class ApplicationEvent extends EventObject{
      ...
      public ApplicationEvent(Object source){
            super(source);
            this.timestamp = System.currentTimeMillis();
      }
   
      public final long getTimestamp(){
            return this.timestamp;
      }
}

ApplicationContext를 통해서 이벤트를 발생시키고 싶은 빈은 ApplicationContextAware 인터페이스를 구현한뒤 ApplicationContext가 제공하는 publishEvent()메서드를 이용해서 이벤트를 발생시키면된다.

public classs MemberService implements ApplicationContextAware{

         private ApplicationContext context;
         public void setApplicationContext(ApplicationContext context){
              this.context = context;
         }

         public void regist(Member member){
               ...
              context.publishEvent(new MemberRegistrationEvent(this, member));
          }
}

이벤트 클래스는 ApplicationEvent클래스를 상속받아 구현하면된다.

public classs MemberRegistrationEvent extends ApplicationEvent{

         private Member member;

         public void MemberRegistrationEvent (Object source, Member member){
              super(source);
              this.member= member;
         }

         public Member getMember(){
               return member;
          }
}

ApplicationContext가 발생시킨 이벤트를 처리할 클래스는 ApplicationListenner 인터페이스를 알맞게 구현해 주면 된다. ApplicationListener인터페이스는 다음과 같이 정의 되어있다.

public interface ApplicationListener<E extends ApplicationEvent> extends EventListener{
        void onApplicationEvent(E event);
}

ApplicationContext는 이벤트 발생시 ApplicationListenner 인터페이스를 구현한빈 객체의 onApplicationEvent() 메서드를 호출함으로서 이벤트를 전달한다. 아래 코드는 ApplicationListenner인터페이스를 구현한 클래스의 전형적인 구현 방식을 보여주고있다.

public classs CustomEventListener implements ApplicationListener<MemberRegistationEvent>{
     
         @Override
         public void onApplicationEvent(MemberRegistationEvent event){
              //원하는 이벤트 처리 코드 삽입
          }
}

ApplicationListenner 인터페이스를 구현한 클래스를 스프링 빈으로 등록해 주기만하면 ApplicationContext가 발생한 이벤트를 전달받아 처리할 수 있게 된다.

<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="customEventListener" class="madvirus.spring.chap03.CustomEventListener"/>
   
</beans>


스프링은 기본적으로 ApplicationContext와 관련된 이벤트를 발생시키고 있는데, 이들 이벤트는 다음과 같다.

org.springframework.context.event.ContextRefreshedEvent : ApplicationContext가 초기화 되거나 설정을 재로딩해서 초기화를재수행할 때 발생한다.
org.springframework.context.event.ContextClosedEvent : ApplicationContext가 종료될 때 발생한다.
org.springframework.context.event.ContextStartEvent : ApplicationContext가 시작될 때 발생한다.
org.springframework.context.event.ContextStoppedEvent : ApplicationContext가 중지될 때 발생한다.

스프링 3.0  부터는 ApplicationListenner에 제네릭이 적용되었기 때문에, 지정한 타입만 처리하는 리스너를 작성할수 있게 되었다.

스프링 2.5 버전는 instanceof 연산자로 객체를 비교했어야했다 P114에 예제있음


==================================프로젝트======================================
예제.
madvirus.spring.chap03
      CustomeventListener (스프링 컨텍스트 이벤트 객체만들기)
      LoginProcessor (클래스내의 메시지 소스를 사용)
      Main (메시지 소스를 이용한 메시지 국제화 처리)
      Main02 (메시지 소스를 이용한 메시지 국제화 처리:강제 영어설정)
      Main03 (클래스내에서 메시지 소스를 사용)
      Main04 (스프링 컨텍스트 이벤트 객체만들기)
      Member (스프링 컨텍스트 이벤트 객체만들기)
      MemberRegistartionEvent (스프링 컨텍스트 이벤트 객체만들기)
      MemberService (스프링 컨텍스트 이벤트 객체만들기)

message
      error.properties
      greeting_en.properties
      greeting_ko.properties

applicationContext.xml


==================================코드======================================

madvirus.spring.chap03
      CustomeventListener (스프링 컨텍스트 이벤트 객체만들기)
package madvirus.spring.chap03;

import org.springframework.context.ApplicationListener;

public class CustomeventListener implements ApplicationListener<MemberRegistartionEvent> {

    @Override
    //MemberRegistartionEvent 객체를 받는다.
    public void onApplicationEvent(MemberRegistartionEvent event) {
        System.out.println("회원 가입 이벤트 발생: " + event.getMember());
    }
}

      LoginProcessor (클래스내의 메시지 소스를 사용)
package madvirus.spring.chap03;

import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;

public class LoginProcessor  implements MessageSourceAware{

    private MessageSource messageSource;
       
    @Override
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
   
    public void login(String username,String password){
        if(!username.equals("medvirus")){
            Object[] args = new String[] { username};
            String failMessage = messageSource.getMessage("login.fail", args, Locale.getDefault());
            throw new IllegalArgumentException(failMessage);
        }
    }
}

      Main (메시지 소스를 이용한 메시지 국제화 처리)
package madvirus.spring.chap03;

import java.util.Locale;

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

public class Main {

    public static void main(String[] args){
        String[] configLocations = new String[] {"applicationContext.xml"};
        ApplicationContext context = new ClassPathXmlApplicationContext(configLocations);
       
        Locale locale = Locale.getDefault();
        String greeting = context.getMessage("greeting",new Object[0], locale);
       
        System.out.println("Default Locale Greeting: "+greeting);
    }
}

      Main02 (메시지 소스를 이용한 메시지 국제화 처리:강제 영어설정)
package madvirus.spring.chap03;

import java.util.Locale;

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

public class Main02 {

    public static void main(String[] args){
        String[] configLocations = new String[] {"applicationContext.xml"};
        ApplicationContext context = new ClassPathXmlApplicationContext(configLocations);
       
        Locale locale = Locale.ENGLISH;
        String greeting = context.getMessage("greeting",new Object[0], locale);
       
        System.out.println("English Locale Greeting: "+greeting);
    }
}

      Main03 (클래스내에서 메시지 소스를 사용)
package madvirus.spring.chap03;

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

public class Main03 {

    public static void main(String[] args){
        String[] configLocations = new String[] {"applicationContext.xml"};
        ApplicationContext context = new ClassPathXmlApplicationContext(configLocations);
       
        LoginProcessor loginProcessor = context.getBean("loginProcessor",LoginProcessor.class);
       
        try{
            loginProcessor.login("madvirus2", "1234");
        }catch(Throwable e){
            System.out.println("예외 발생 : "+e.getMessage());
        }       
    }
}

      Main04 (스프링 컨텍스트 이벤트 객체만들기)
package madvirus.spring.chap03;

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

public class Main04 {
   
    public static void main(String[] args){
        String[] configLocations = new String[] {"applicationContext.xml"};
        ApplicationContext context = new ClassPathXmlApplicationContext(configLocations);
       
        MemberService memberService = context.getBean("memberService",MemberService.class);
       
        memberService.regist(new Member("madvirus", "최범균"));
    }
}

      Member (스프링 컨텍스트 이벤트 객체만들기)
package madvirus.spring.chap03;

public class Member {
 
    private String id;
    private String name;
   
    public Member(String id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Member [id=" + id + ", name=" + name + "]";
    }   
}

      MemberRegistartionEvent (스프링 컨텍스트 이벤트 객체만들기)
package madvirus.spring.chap03;

import org.springframework.context.ApplicationEvent;

public class MemberRegistartionEvent extends ApplicationEvent {

    private Member member;   

    public MemberRegistartionEvent(Object source, Member member) {
        super(source);
        this.member = member;
    }
    public Member getMember() {
        return member;
    }
}

      MemberService (스프링 컨텍스트 이벤트 객체만들기)
package madvirus.spring.chap03;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class MemberService implements ApplicationContextAware {

    private ApplicationContext applicationContext;
   
    //객체를 받을수있도록 setter를 만듬
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void regist(Member member){
        //publishEvent 를 불러 이벤트 처리
        applicationContext.publishEvent(new MemberRegistartionEvent(this, member));
    }
}

message
      error.properties
login.fail=Member ID {0} is not matching password

      greeting_en.properties
greeting=Hello!

      greeting_ko.properties
greeting=안녕하세요!


applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    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
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- 국제화 처리를 위한 리소스 번들지정  -->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>message.greeting</value>
                <value>message.error</value>
            </list>       
        </property>
    </bean>
   
    <!-- 빈 객체에서 메시지 이용하기 -->
    <bean id="loginProcessor" class="madvirus.spring.chap03.LoginProcessor"/>
   
    <!-- 스프링 컨텍스트 이벤트 객체만들기 -->
    <bean id="memberService" class="madvirus.spring.chap03.MemberService"/>
    <bean class="madvirus.spring.chap03.CustomeventListener"/>
   
</beans>

==================================결과값=====================================

1. Main (메시지 소스를 이용한 메시지 국제화 처리)

2. Main02 (메시지 소스를 이용한 메시지 국제화 처리) - locale 처리

3.클래스내에서 메시지 소스를 사용

4.스프링 컨텍스트 이벤트 객체만들기


'스프링3.0' 카테고리의 다른 글

Spring3.0 DI 3  (0) 2012.05.14
스프링 3.0 @ 어노테이션 기반 설정  (0) 2012.05.14
Spring3.0 Di 2  (0) 2012.05.14
Spring3.0 DI AOP  (0) 2012.05.14
스프링 3.0 강좌  (0) 2012.05.11
Posted by 사라링

BLOG main image
.. by 사라링

카테고리

사라링님의 노트 (301)
JSP (31)
J-Query (41)
JAVA (24)
VM-WARE (0)
디자인패턴 (1)
스크랩 (0)
스트러츠 (3)
안드로이드 (11)
오라클 (45)
우분투-오라클 (1)
이클립스메뉴얼 (6)
스프링3.0 (23)
자바스크립트 (10)
HTML5.0 (17)
정보처리기사 (1)
기타(컴퓨터 관련) (1)
문제점 해결 (3)
프로젝트 (2)
AJAX (4)
하이버네이트 (3)
트러스트폼 (11)
Jeus (2)
재무관리(회계) (5)
정규식 (5)
아이바티스 (8)
취미 (2)
소프트웨어 보안 관련모음 (0)
정보보안기사 (6)
C언어 베이직 및 프로그램 (3)
보안 관련 용어 정리 (2)
넥사크로 (6)
Total :
Today : Yesterday :