在Spring Boot环境中实现自定义注释

时间:2020-07-15 07:57:29

标签: java spring-boot java-annotations

我想在Spring Boot环境中创建和实现注释

  • 通过HttpServletRequest获取cookie值以从某些服务获取UserDto
  • 我想通过下面的注释(@UserInfo)插入它,但是我不知道如何访问它

像下面的代码

@RequestMapping("/test")
    public test (@UserInfo UserDto userDto) {
        Syste.out.println(userDto.getUserId());
}

1 个答案:

答案 0 :(得分:0)

这里是一个例子。我没有所有要求,但我认为足以为您提供帮助:

@Aspect
@Component
public class AspectConf {

    @Autowired
    private UserService userService;

    @Pointcut("execution(@org.springframework.web.bind.annotation.RequestMapping * *(..))")
    public void requestMappingAnnotatedMethod() {}
    
    @Before("requestMappingAnnotatedMethod()")
    public void beforeAuthorizeMethods(final JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        //do something with cookies: request.getCookies();
        
        Object userInfoAnnotatedArgument = getUserInfoAnnotatedParameter(joinPoint);
        if(userInfoAnnotatedArgument != null) {
            ((UserDto)userInfoAnnotatedArgument).setName("xsxsxsxsx");
            //get `userInfo` from `userService` and update `dto`
            ((UserDto)userInfoAnnotatedArgument).setXXX(...);
        }
    }

    private Object getUserInfoAnnotatedParameter(final JoinPoint joinPoint) {
        final MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        
        Method method = methodSignature.getMethod();
        Object[] arguments = joinPoint.getArgs();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            Annotation[] annotations = parameters[i].getAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation.annotationType() == UserInfo.class) {
                    return arguments[i];
                }
            }        
        }
        return null;
    }
}