因为拦截器在 Bean 初始化之前进行,所以在拦截器中无法像这样注入 Bean
为了解决这个问题,我们在拦截器方法里,创建一个 BeanFactory 的实例,然后调用其 getBean() 方法来获取我们需要的 Bean 实例。
比如我们这里需要获取 userRepoditory 对象,可以这样(37-38行)
方法二、推荐
WebMvcConfig.java 监听器
SessionInterceptor 拦截器
参考:
https://stackoverflow.com/questions/23349180/java-config-for-spring-interceptor-where-interceptor-is-using-autowired-spring-b
https://my.oschina.net/gmd/blog/699385
- @Autowired
- private UserRepository userRepository;
方法一、
为了解决这个问题,我们在拦截器方法里,创建一个 BeanFactory 的实例,然后调用其 getBean() 方法来获取我们需要的 Bean 实例。
比如我们这里需要获取 userRepoditory 对象,可以这样(37-38行)
- public class SessionInterceptor implements HandlerInterceptor {
- @Autowired
- private UserRepository userRepository;
- /**
- * 在请求处理之前进行调用(Controller方法调用之前)
- */
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- return true;
- }
- /**
- * 在请求处理之后调用,但是在视图被渲染之前(Controller方法调用之后)
- *
- * @param request
- * @param response
- * @param handler
- * @param modelAndView
- * @throws Exception
- */
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
- System.out.println("拦截了");
- if(request.getSession().getAttribute("user") == null) {
- //如果用户授权存在,添加Session
- try {
- SecurityContext securityContext = SecurityContextHolder.getContext();
- Authentication authentication = securityContext.getAuthentication();
- Object principal = authentication.getPrincipal();
- if (principal != null && principal instanceof UserDetails) {
- String username = ((UserDetails) principal).getUsername();
- if(userRepository == null) {
- BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
- userRepository = (UserRepository) factory.getBean("userRepository");
- User user = userRepository.findByUsername(username);
- request.getSession().setAttribute("user", user);
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * 在整个请求调用之后被调用,也就是在 DispatcherServlet 渲染了对应的视图后执行(主要用于资源清理)
- *
- * @param request
- * @param response
- * @param handler
- * @param ex
- * @throws Exception
- */
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
- }
- }
方法二、推荐
WebMvcConfig.java 监听器
- @Configuration
- public class WebMvcConfig implements WebMvcConfigurer {
- @Bean
- SessionInterceptor sessionInterceptor() {
- return new SessionInterceptor();
- }
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- //拦截器按照顺序执行
- registry.addInterceptor(sessionInterceptor())
- .addPathPatterns("/**")
- .excludePathPatterns("/components/**","/css/**","/js/**","/img/**","/logout");
- }
- }
SessionInterceptor 拦截器
- public class SessionInterceptor implements HandlerInterceptor {
- @Autowired
- private UserRepository userRepository;
- @Autowired
- private UserService userService;
- /**
- * 在请求处理之前进行调用(Controller方法调用之前)
- */
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
- return true;
- }
- /**
- * 在请求处理之后调用,但是在视图被渲染之前(Controller方法调用之后)
- *
- * @param request
- * @param response
- * @param handler
- * @param modelAndView
- * @throws Exception
- */
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
- UserVO userSession = (UserVO) request.getSession().getAttribute("user");
- if (userSession == null) {
- //如果用户授权存在,添加Session
- if (SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().isAuthenticated()
- && !SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString().equals("anonymousUser")) {
- User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
- User user = userRepository.findByUsername(principal.getUsername());
- UserVO userVO = userService.getUserVO(user);
- request.getSession().setAttribute("user", userVO);
- }
- }
- }
- /**
- * 在整个请求调用之后被调用,也就是在 DispatcherServlet 渲染了对应的视图后执行(主要用于资源清理)
- *
- * @param request
- * @param response
- * @param handler
- * @param ex
- * @throws Exception
- */
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
- }
- }
参考:
https://stackoverflow.com/questions/23349180/java-config-for-spring-interceptor-where-interceptor-is-using-autowired-spring-b
https://my.oschina.net/gmd/blog/699385
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏