Method Injection
Dependency Injection의 방법인 setter injection과 constructor
injection을 사용할 경우, Singleton Bean은 Singleton Bean 만을 유지하게
된다. 그런데 특별한 경우에는 Singleton Bean이 Non Singleton Bean(즉,
Prototype Bean)과 Dependency 관계를 가질 수 있다. 이 같은 상황이 발생할 때
Lookup Method Injection을 사용하여 해결하는 것이 가능하다. 동일한 상황에서
BeanFactoryAware를 구현하여 해결하는 방법도 존재하나 Spring Container API에
종속적으로 Bean 코드가 변경되므로 바람직한 해결방법이 아니다.
Lookup Method Injection
Singleton Bean이 Prototype Bean을 참조관계로 사용할 때 lookup-method 요소를 설정한다.
다음은 Lookup Method Injection의 요소를 정의한 속성 정의 파일인
applicationContext-user-method.xml
의 일부이다.
<bean id="com.sds.emp.user.services.UserServiceWithIoCBasic"
class="com.sds.emp.user.services.impl.UserServiceImplWithIoCBasic">
<!-- method injection -->
<lookup-method name="getUserDAO" bean="userDAO"/>
</bean>
<!-- change scope from singleton to prototype (non singleton) -->
<bean id="userDAO" class="com.sds.emp.user.services.impl.UserDAOWithIoCBasic" scope="prototype"/>
해당 lookup 메소드는 다음과 같이 UserDAOWithIoCBasic를 리턴하는 메소드 형태로 구현하도록 한다.
public class UserServiceImplWithIoCBasic ...
public UserDAOWithIoCBasic getUserDAO(){
// do nothing - this method will be overrided by Spring Container
return null;
}
Method Replacement
이미 존재하는 기존의 메소드를 수정하지 않은 상태에서 메소드의 기능을 변경할 때 replaced-method 요소 설정한다.
사용 예제는 다음과 같다.
- 구현 클래스
import org.springframework.beans.factory.support.MethodReplacer;
public class SayHelloMethodReplacer implements MethodReplacer {
public Object reimplement(Object target, Method method, Object[] args) throws Throwable {
…중략
- 속성 정의 파일
<bean id="beanFirst" class="test.BeanFirst"/>
<bean id="beanSecond" class=" test.BeanFirst">
<replaced-method name="sayHello" replacer="methodReplacer">
<arg-type>String</arg-type>
</replaced-method>
</bean>
<bean id="methodReplacer" class="test.SayHelloMethodReplacer"/>
Resources
다운로드
샘플 테스트 코드를 포함하고 있는 anyframe-iocbasictest-src.zip 파일을 다운받은 후, 테스트 환경 설정을 참조하여
위에서 제시한 예제 코드를 실행해 볼 수 있다.
| Name |
Download |
| anyframe-iocbasictest-src.zip |
Download |
참고자료