当前位置: 首页>编程语言>正文

spring boot method spring boot methodinterceptor

正常情况下,spring 中的拦截器是不能直接 使用 @Autowired注入对象 ,  如果需要在拦截器中注入service 或者配置,需要将这个拦截器交给spring管理,并且在注册拦截器时使用spring管理的bean,这才会让@Autowired注解生效。

如下操作:  (要注意我使用的注解)

 

1、新建interceptor

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Component;

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

@Component
public class MyInterceptor implements HandlerInterceptor {
    
    @Value("${check-login.flag}")
    private Boolean flag;

    @Autowired
    private SysUserService sysUserService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // return true 为放行,false为拦截掉
        System.out.println("进入了拦截器");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

2、注册interceptor

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {
    
    @Resource
    private MyInterceptor myInterceptor;
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor)
                .addPathPatterns("/**")    // 要拦截的路径
                .excludePathPatterns("/login", "/error");   // 要排除的路径
    }
}

 




https://www.xamrdz.com/lan/53h1967481.html

相关文章: