backend/Spring

[Spring] 빈 묶기(Bean wiring)

버리야 2008. 2. 5. 14:22
반응형

빈 묶기(Bean wiring)


XML로 묶기 : 다음을 이용해 스프링 컨테이너가 XML을 통한 빈 묶기를 지원한다.

XmlBeanFactory

ClassPathXmlApplicaionContext

FileSystemXmlApplicationContext

XmlWebApplicationContext


프로토타입과 싱글톤 비교

스프링의 모든 빈은 싱글톤. getBean()의 호출에 의해서든 묶기를 통해서든 간에, 컨테이너가 빈을 배포할 때에는 항상 그 빈의 완전히 동일한 인스턴스를 내줄 것이다.

scope="singleton"
scope="prototype"



프로토타입 빈을 정의하는 것이 유리할 때

프로토타입을 정의한다는 것은 실제 하나의 빈을 정의하는 것이 아닌, 청사진을 정의한다는 의미다. 그 다음엔 그 청사진을 바탕으로 빈들이 생성될 것이다.

프로토타입 빈은, 빈을 요청할 때마다 컨테이너가 빈의 유일한 인스턴스를 제공하기 원하면서도 그 빈의 하나 이상의 특성을 스프링을 통해 설정하고자 할 경우에 유용


프로토타입으로 정의

<bean id=”foo” class= ”com.spring.Foo” singleton=false” />

<bean id="foo" class="com.spring.Foo" scope="prototype" />

빈 의 이름을 사용해 getBean()을 호출할 때마다 프로토타입의 새로운 인스턴스가 생성된다. 이로 인해 데이터베이스나 네트워크 연결과 같은 제한된 자원을 사용하는 빈의 경우에는 적합하지 않다. 최소한 새로운 인스턴스가 생성될 때마다 약간의 성능 저하를 겪을 수 있기 때문에, 절대적으로 필요한 경우에만 프로토타입으로 빈을 정의하자.


참고)
dW문서  
'Spring 2.0: 요란스럽지 않은 진화의 흐름' 내용 중

Spring의 기반을 이루는 IoC 컨테이너에서는 앞서 언급한 XML 설정 이외에 빈(bean)의 스코프(scope)가 추가된 것이 주요 개선 사항이다.

Singleton과 prototype으로만 존재하던 스코프에 request, sessionglobal session 스코프가 추가되었고, 사용자가 정의한 스코프를 사용할 수도 있다. 이러한 개선은 개발자가 직접 HTTP Request나 Session을 다루는 일을 줄여주고, 웹 어플리케이션의 커뮤니케이션 불연속성 문제를 다소나마 해결해줄 것으로 보인다.


Scope Description

singleton

Scopes a single bean definition to a single object instance per Spring IoC container.

prototype

Scopes a single bean definition to any number of object instances.

request

Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session

Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session

Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.


출처 : spring 2.0 reference 중

 

초기화와 소멸

빈의 정이 내에 커스텀 init-method를 선언함으로써 빈이 인스턴스화되는 즉시 호출될 메소드를 지정할 수 있다.

커스텀 destroy -method는 빈이 컨테이너로부터 제거되기 직전에 호출될 메소드를 지정한다.


<bean id=”foo” class= ”com.spring.Foo” init-method= ”setup ” destroy -method= ”teardown” />


Example) 커넥션 풀링(connection pooling) 빈


public class MyConnectionPool{

public void initialize(){

//커넥션 풀 초기화

}

}

public void close(){

//연결 해제

}

}


빈의 정의는,

<bean id=”connectionPool” class= ”com.spring.MyConnectionPool” init-method= ”initialize” destroy-method= ”close” />


MyConnectionPool이 인스턴스화되자마자 initialize() 메소드가 호출,

빈이 컨테이너로부터 제거되기 직전에 close() 메소드를 호출


스프링은 또 다른 방법으로, InitializingBean과 DisposableBean이라는 동일한 역할을 하는 두개의 인터페이스를 제공한다.


InitializingBean 인터페이스는 afterPropertiesSet() 메소드 : 빈의 모든 특성이 설정된 후에 한 번 호출.

DisposableBean 인터페이스는 destroy () : 빈이 컨테이너로부터 제거될 때 호출



이 방법은 인터페이스를 구현하는 빈을 스프링 컨테이너가 자동으로 탐지하며, 별다른 설정없이도 메소드를 호출해준다(XML 손대지 않고) 하지만, 인터페이스를 구현하게 되면, 빈은 스프링의 API에 묶이게 되어 버린다.

빈을 초기화하고 소멸시킬 때 가능하다면 init-method와 destroy-method 정의에 의존하는게 좋은 방법이다. 스프링의 인터페이스를 사용할만한 유일한 경우는 스프링 컨테이너 안에서 특별하게 사용될 프레임워크 빈을 개발할 때뿐이다.




반응형