Spring拦截器依赖注入

时间:2013-12-23 08:41:36

标签: spring-mvc

我有springmvc和angularjs app启动并运行。 在Springmvc中,我有一个名为userSessionBean的bean。 现在我正在为spring mvc添加一个拦截器,在我的pre handel方法中,我试图访问userSessionBean。

我的问题是“我可以在拦截器中注入userSessionBean”

/**
* 
*/
package com.loginLite.remote.authentication.interceptors;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.remote.authentication.model.UserSessionBean;

/**
 * @author jamju02
*
*/
public class AuthenticationInteceptor implements HandlerInterceptor {
@Autowired
private UserSessionBean userSessionBean = null;

/**
 * @return the userSessionBean
 */
public UserSessionBean getUserSessionBean() {
    return userSessionBean;
}

/**
 * @param userSessionBean the userSessionBean to set
 */
public void setUserSessionBean(UserSessionBean userSessionBean) {
    userSessionBean = userSessionBean;
}

@Override
public boolean preHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler) throws Exception {

    System.out.println("Pre-handle");

    return true;
}

@Override
public void postHandle(HttpServletRequest request,
        HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {
    Random rnd = new Random();
    int tokenNumber = 100000 + rnd.nextInt(900000);
    userSessionBean.setAuthTokenNumber(String.valueOf(tokenNumber));
     response.addHeader("AUTH_TOKEN",userSessionBean.getAuthTokenNumber());
    System.out.println("Post-handle");
}

@Override
public void afterCompletion(HttpServletRequest request,
        HttpServletResponse response, Object handler, Exception ex)
        throws Exception {
    System.out.println("After completion handle");
}

}

我的调度程序servlet

<mvc:interceptors>
  <bean class="com.paychex.loginLite.remote.authentication.interceptors.AuthenticationInteceptor">
    <property name="userSessionBean" ref="userSessionBean"></property>
  </bean>
</mvc:interceptors> 


<bean id="userSessionBean"
    class="com.paychex.loginLite.remote.authentication.model.UserSessionBean"
    scope="session">
    <aop:scoped-proxy />
</bean>

1 个答案:

答案 0 :(得分:-1)

我终于能够解决我困扰我的问题了。 错误是,我正在为我的拦截器类实现接口“HandlerInterceptor”,只要我删除了接口并且扩展类“HandlerInterceptorAdapter”依赖注入就开始正常工作了。