InitializingBean 인터페이스

빈 객체의 라이프 사이클과 관련된 인터페이스 중에서 가장 많이 사용되는 것 중의 하나가
  org.springframework.beans.factory.InitializingBean 인터페이다.
 
  객체를 생성하고 프로퍼티를 초기화 하고, 컨테이너관련 설정을 완료한 뒤에 호출되는 메서드를 정의하고 있다.
 
  public interface InitializingBean {
    public void afterPropertiesSet() throws Exception
  }
 
  afterPropertiesSet() 메서드는 주로 빈 객체의 프로퍼티가 모두 올바르게 설정되었는지의 여부를 검사하는 용도
  (프로퍼티 값을 검증하는 코드를 구현)
 
  public abstract class AbstractUrlBasedView extends AbstractView implements InitializingBean {
    ...
    public void afterPropertiesSet() throws Exception {
      if( getUrl() == null ) {
        throw new lllegalArgumentException("Property 'url' is required");
      }
    }
    ...
  }

-- 위 설정을 보면 세 개의 빈은 이름만 다를 뿐 <bean> 에서 가지고 있는 <property> 값이 대부분 동일하다.
   이렇게 중복되는 설정을 갖는 빈이 다수 존재할 경우, 중복되는 설정 정보를 담고 있는 부모빈을 정의한 뒤, 부모 빈 정보를
   재사용하도록 설장할 수 있다. 부모 빈으로 부터 설정 정보를 상속받는 예
<bean id="doorMonitor" class="madvirus.spring.chap02.SystemMonitor">
  <property name="periodTime" value="10" />
  <property name="sender" ref="smsSender" />
</bean>

<bean id="lobbyMonitor" class="madvirus.spring.chap02.SystemMonitor">
  <property name="periodTime" value="10" />
  <property name="sender" ref="smsSender" />
</bean>

<bean id="roomMonitor" class="madvirus.spring.chap02.SystemMonitor">
  <property name="periodTime" value="10" />
  <property name="sender" ref="smsSender" />
</bean>


<bean id="commonMonitor" class="madvirus.spring.chap02.SystemMonitor" abstract="true">
  <property name="periodTime" value="10" />
  <property name="sender" ref="smsSender" />
</bean>
※ abstract 속성 값을 "true" 지정하면 스프링 컨테이너는 해당 빈 객체를 생성하지 않는다.
  commonMonitor 빈은 설정정보만 존재할 뿐 실제로 객체는 생성되지 않는다.

<bean id="lobbyMonitor" parent="commonMonitor">
</bean>
<bean id="roomMonitor" parent="commonMonitor">
</bean>
<bean id="doorMonitor" parent="commonMonitor">
  <property name="periodTime" value="20" />
</bean>
※ 자식 빈에서는 parent 속성을 사용하여 클래스 및 프로퍼티 설정 정보를 물려 받을 부모빈을 설정한다.
   그래서 자식 빈에서는 class명 설정이 없어도 부모빈의 class 설정정보를 물려받는다.
   변경하고자 하는 값이 있다면, 추가로 입력해주면된다.( property , class 모두 공통 )

 - java.util.Properties 클래스는특별한 타입의 Map으로서 이 모두 String 인 Map 이다.

보통 Properties 클래스는 환경변수나 설정 정보와 같이 상황에 따라 변경되는 값을 저장

하기 위한 용도로 주로 사용된다.


스프링에서 <props> 태그를 이용하여 Properties 타입의 프로퍼티설정 방법

예제)

-- properties 설정

<bean naem="client" class="madvirus.spring.chap02.bookClient">

<property name="config">

<props>

<prop key="server">192.168.1.100</prop>

<prop key="connectionTimeout">5000</prop>

</props>

</property>

</bean>


-- properties 사용

public class BookClient {

private Properties config;

public void setConfig(Properties config) {

this.config = config;

}


public void connect() {

String serverIp = config.getProperty("server");

...

}

}


- 자주 값이 바뀌는 정보를 Properties 를 사용해서 설정을 한다는데..

그냥 <value> 로 해서 가져다가 쓰는거랑 모가 다른지는...

어떨때 저걸써야되는지는 확~ 느낌이 오진 않는다...

+ Recent posts