拦截器中获取注解 来源:https://blog.csdn.net/wangmx1993328/article/details/81030268/
public class JWTInterceptor implements HandlerInterceptor { private SysSettingService sysSettingService; //构造函数传入Service public JWTInterceptor(SysSettingService _sysSettingService) { sysSettingService = _sysSettingService; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { //方法处理器, 请求的目标方法。RequirePermissions是自定义注解。 HandlerMethod handlerMethod = (HandlerMethod) handler; //1: 获取目标方法上的指定注解,不存在时,返回 Null RequirePermissions methodPermissions = handlerMethod.getMethodAnnotation(RequirePermissions.class); //2: 获取目标方法所在类上的指定注解,不存在时,返回 Null RequirePermissions classPermissions = handlerMethod.getMethod().getDeclaringClass().getAnnotation(RequirePermissions.class); if (methodPermissions != null) { //获取注解中的数据 String[] permissions = methodPermissions.values(); } }
} }
拦截器中注入Service
方式1,使用构造函数注入
/** * 系统配置 */ @Configuration public class SysMvcConfig implements WebMvcConfigurer { @Autowired private SysSettingService sysSettingService; /** * 注册拦截器 */ @Override public void addInterceptors(InterceptorRegistry registry) { var reg = registry.addInterceptor(new JwtInterceptor(sysSettingService)); // 此地址下的请求都需要使用此过滤器 reg.addPathPatterns("/SysSetting/**"); } }
对应拦截器代码
public class JWTInterceptor implements HandlerInterceptor { private SysSettingService sysSettingService; public JWTInterceptor(SysSettingService _sysSettingService) { sysSettingService = _sysSettingService; } }
方式2,将自定义拦截器作为 Bean 写入配置,使用这个Bean注入拦截器,然后拦截器中就可以使用@Autowired自动注入Service。
@Configuration public class SysMvcConfig implements WebMvcConfigurer { /** * 将自定义拦截器作为 Bean 写入配置,使用这个Bean注入拦截器,然后拦截器中就可以使用@Autowired自动注入Service。 * */ @Bean public JWTInterceptor jwtInterceptor(){ return new JWTInterceptor(); } /** * 注册拦截器 */ @Override public void addInterceptors(InterceptorRegistry registry) { var reg = registry.addInterceptor(jwtInterceptor()); // 此地址下的请求都需要使用此过滤器 reg.addPathPatterns("/SysSetting/**"); } }
对应拦截器注入Service代码
public class JWTInterceptor implements HandlerInterceptor { @Autowired private SysSettingService sysSettingService; }