티스토리 뷰

스프링 프레임워크를 사용해서 개발하다가 빈(Bean)들의 ID값(String)을 가지고 ApplicationContext 객체로 부터 동적으로 객체를 얻고 싶었다. 하지만 ApplicationContext 객체를 어디서 얻어야 할지 고민이 들었다.

String configLocation = "META-INF/spring/app-context.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(configLocation);

이 때 생성한 ApplicationContext 객체를 클래스 인자값으로 건네건네 받아야만 하나..? 아무리봐도 이건 아니었다. 그렇게 무식한 프레임워크였으면 사용하지도 않았을 것이다. 어딘가 어노테이션을 이용하던 그외의 다른 방법이든 간에, 어느곳에 있더라도 ApplicationContext  객체를 리턴받을 방법을 마련해 놓았겠지 하며 찾았다. 역시나 있다.




ApplicationContextAware 인터페이스


ApplicationContextAware 인터페이스를 구현하기만 하면 ApplicationContext 객체를 얻는 것은 식은죽 먹기다.

public interface ApplicationContextAware {
	void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}

구현할 메소드는 하나 뿐이다. 이 메소드를 구현하기만 하면, 스프링 프레임워크에서 인자값(applicationContext 변수)으로 객체를 넘겨준다. 그것을 우리는 멤버변수로 전달하던 좀 가공해서 Map 형태로 가지고 있던 그건 사용자 마음이다.



내 경우는 특정 타입에 속한 빈(Bean)들을 조회할 경우였으므로, getBeansOfType 을 이용해 바로 Map 객체로 가져왔다.

@Component
public class Login implements ApplicationContextAware {
	
	private Map<String, Screen> screens;
	
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.screens = applicationContext.getBeansOfType(Screen.class);
	}
}


반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함