0

I want to create and implement annotation in spring boot environment

  • Get cookie value through HttpServletRequest to get UserDto from some service
  • And I want to insert it through the annotation below (@UserInfo), but I don't know how to access it

like below code

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

1 Answers1

0

Here is an example. I don't have all requirements but I think it will be enough to help you:

@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;
    }
}
Planck Constant
  • 1,406
  • 1
  • 17
  • 19