스프링을 사용하여 종속성을 httpsessionlistener에 주입하는 방법은 무엇입니까?
-
19-09-2019 - |
문제
스프링을 사용하여 httpsessionListener에 종속성을 주입하는 방법, context.getBean("foo-bar")
?
해결책
Servlet 3.0 ServletContext에는 "AddListener"메소드가 있으므로 Web.xml 파일에 리스너를 추가하는 대신 다음과 같은 코드를 통해 추가 할 수 있습니다.
@Component
public class MyHttpSessionListener implements javax.servlet.http.HttpSessionListener, ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (applicationContext instanceof WebApplicationContext) {
((WebApplicationContext) applicationContext).getServletContext().addListener(this);
} else {
//Either throw an exception or fail gracefully, up to you
throw new RuntimeException("Must be inside a web application context");
}
}
}
즉, "myhttpsessionListener"에 정상적으로 주입 할 수 있음을 의미하며,이를 통해 단순히 응용 프로그램 컨텍스트에 Bean이 있으면 리스너가 컨테이너에 등록됩니다.
다른 팁
당신은 당신의 선언 할 수 있습니다 HttpSessionListener
스프링 컨텍스트에서 콩으로, 대표단 대리인을 실제 청취자로 등록하십시오. web.xml
, 이 같은:
public class DelegationListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent se) {
ApplicationContext context =
WebApplicationContextUtils.getWebApplicationContext(
se.getSession().getServletContext()
);
HttpSessionListener target =
context.getBean("myListener", HttpSessionListener.class);
target.sessionCreated(se);
}
...
}
Spring 4.0을 사용하면 3과 함께 작동하며 아래에 자세히 설명한 예제를 구현했습니다. ApplicationListener<InteractiveAuthenticationSuccessEvent>
그리고 주입 HttpSession
https://stackoverflow.com/a/19795352/2213375
제휴하지 않습니다 StackOverflow