如何在spring引导过滤器中获得自定义注解

nkcskrwz  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(514)

我有一个带有自定义过滤器的spring boot应用程序:

import javax.servlet.Filter

public class MyFilter implements Filter{

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        System.out.println("MyFilter");
    }
}

应用程序中的某些控制器在其方法上具有自定义注解。所有自定义注解都实现myannotation接口。

@GetMapping("/")
    @MyCustomAnnotation
    @AnotherCustomAnnotation
    public ResponseEntity<String> get(){
        addSomeMetric();
        return new ResponseEntity<>("Hello world", HttpStatus.OK);
    }

如何从dofilter代码中获取在uri端点上定义的所有注解的列表?

w8biq8rn

w8biq8rn1#

springaop可用于根据请求/用户来决定是否需要执行控制器方法。
下面的代码是实现相同功能的一种方法。

@Aspect
@Component
public class AnnotationFilterAspect {

    @Pointcut("execution(public * package.controller..*(..))")
    public void allControllerMethods() {

    }

    @Around("allControllerMethods()")
    public Object checkAccess(ProceedingJoinPoint pjp) {
        Object retObject = null;
        Method method = getMethod(pjp);
        for(Annotation anno : method.getAnnotations()){
            System.out.println(anno.annotationType());
            // Annotation details
        }

        // Logged in user details
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        //or
        //Get the HttpServletRequest currently bound to the thread.
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();

        // Logic to proceed to the controller method based on the logged in user or request can be done here. 

        try {
            retObject = pjp.proceed();
        } catch (Throwable e) {
            // Handle the exception
        }

        return retObject;
    }

    //Refer : https://stackoverflow.com/q/5714411/4214241
    private Method getMethod(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        if (method.getDeclaringClass().isInterface()) {
            try {
                method= pjp.getTarget().getClass().getDeclaredMethod(pjp.getSignature().getName(),
                        method.getParameterTypes());
            } catch (final SecurityException exception) {
                //...
            } catch (final NoSuchMethodException exception) {
                //...                
            }
        }   
        return method;
    }

}

还要注意,注解retentionpolicy必须是运行时的,这样代码才能工作。

kxeu7u2r

kxeu7u2r2#

我最终使用了一个handler拦截器而不是过滤器。
因为我只针对web请求,所以它似乎是比aop更好更简单的解决方案。

@Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
       MyAnnotation myAnnotation = getMyAnnotation(handler);

    }

    private MyAnnotation getMyAnnotation(Object handler) {
       HandlerMethod handlerMethod = (HandlerMethod) handler;
       Method method = handlerMethod.getMethod();
       return method.getAnnotation(MyAnnotation.class);
}

相关问题