【问题标题】:implement custom annotation in spring boot environment在spring boot环境中实现自定义注解
【发布时间】:2020-11-04 16:09:28
【问题描述】:

我想在spring boot环境中创建并实现注解

  • 通过HttpServletRequest获取cookie值,从某个服务获取UserDto
  • 我想通过下面的注解插入(@UserInfo),但是不知道怎么访问

如下代码

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

【问题讨论】:

  • 你知道如何使用AOP吗?
  • 哦,正确的 AOP!我差点忘了。谢谢!!

标签: java spring-boot java-annotations


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 2019-04-07
    • 2022-01-04
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多