简体   繁体   English

在 spring 启动环境中实现自定义注解

[英]implement custom annotation in spring boot environment

I want to create and implement annotation in spring boot environment我想在 spring 引导环境中创建和实现注释

  • Get cookie value through HttpServletRequest to get UserDto from some service通过 HttpServletRequest 获取 cookie 值以从某个服务获取 UserDto
  • And I want to insert it through the annotation below (@UserInfo), but I don't know how to access it而且我想通过下面的注解(@UserInfo)插入,但是不知道怎么访问

like below code像下面的代码

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

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM