web.xml에서 정의하는 filter들은 기본적으로 servlet container(was)에 의해서 control됩니다. 이 것들은 spring과는 아무런 관련이 없는 것들이죠. 따라서, spring framework에서 사용하는 DI 즉, @Autowired 같은 것들을 사용할 수 없습니다.
어떻게 하면 DI를 가능하게 할 수 있을까요?
org.springframework.web.filter.DelegatingFilterProxy
위 Class가 그것을 가능하게 해 줍니다. 아래 web.xml 설정을 보시죠.
<filter> <filter-name>myfilter</filter-name> <filter-class> org.springframework.web.filter.DelegatingFilterProxy </filter-class> </filter> <filter-mapping> <filter-name>myfilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping>
위 설정은 *.do와 같은 형태로 들어오는 request를 DelegatingFilterProxy가 처리한다는 설정입니다. 그런데, 이 Class는 좀 특이하게 행동합니다. 아래는 Filter class 입니다.
package per.yym.filter; // import 생략 @Service("myfilter") public class MySpecialFilter implements Filter { @Autowired UserService userservice; @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { .. 생략 String message = messageBuilder.getErrorMessage("AUTH_ERROR"); filterChain.doFilter(request, response); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
위 Class의 @Service Value인 “myfilter”에 주목해 주십시오.
web.xml의 filter-name과 일치합니다.
DelegatingFilterProxy는 자신이 직접 request를 처리하는 것이 아니라, filter-name에 정의된 이름을 ID로 사용하는 Class instance를 Spring으로부터 얻어서 그 것이 처리하도록 Proxy 역할을 합니다.
그리고, 위 Class는 @Service로 정의되어 있기 때문에 Spring bean이고, 그렇게 때문에, @Autowired를 사용할 수 있습니다.
맘에 드네요 ^^
1. 클래스 선언
@Component
public class ImsClassDispatcher implements ApplicationContextAware {
public static ApplicationContext applicationContext;
@SuppressWarnings(“static-access”)
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
2. 사용
PopupMgmtService popupMgmtService = (PopupMgmtService) ImsClassDispatcher.applicationContext.getBean(“PopupMgmtService”);
위와 같이 하시면 됩니다
좋아요좋아요