AOP切面 获取自定义参数注解 (@Target(ElementType.PARAMETER))

AOP切面 获取自定义参数注解 @Target(ElementType.PARAMETER)

1.创建自定义参数注解

package com.joolun.cloud.weixin.mp.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface User {
}

这里@Target中的类型用的是PARAMETER,因为我这里的注解要用到参数中。比如:

	@ApiOperation("查询我的定制")
	@GetMapping("/myCustomProduct")
	public R myCustomProduct(@User UserVo userVo) {
		
		return R.ok(userVo);
	}

2.编写自定义注解解析器

package com.joolun.cloud.weixin.mp.resolver;


import com.joolun.cloud.common.core.util.R;
import com.joolun.cloud.weixin.mp.annotation.User;
import com.joolun.cloud.weixin.mp.constant.RedsKeyConstant;
import com.joolun.cloud.weixin.mp.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


@Component
public class UserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
       // return methodParameter.getParameterType().isAssignableFrom(UserVo.class) && methodParameter.hasParameterAnnotation(User.class);
        return methodParameter.hasParameterAnnotation(User.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取用户信息
        String openId = nativeWebRequest.getHeader("uuid");
        UserVo user = (UserVo) redisTemplate.opsForValue().get(RedsKeyConstant.SESSION_USER_UUID+openId);
        if(user==null||openId==null) {            
            return null;
        }

        return user;
    }


}

3.实现WebMvcConfigurer接口,重写addArgumentResolvers方法配置解析器

package com.joolun.cloud.weixin.mp.resolver;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;


@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    private UserHandlerMethodArgumentResolver userHandlerMethodArgumentResolver;


    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(userHandlerMethodArgumentResolver);
    }
}

4.创建切面

package com.joolun.cloud.weixin.mp.annotation;

import com.joolun.cloud.common.core.util.R;
import com.joolun.cloud.weixin.mp.vo.UserVo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Aspect
@Component
public class LoginUserTokenAspect {

    @Around("within(com.joolun.cloud.weixin.mp.controller.PubController) || within(com.joolun.cloud.weixin.mp.controller.HomeController) ")
    public Object run(ProceedingJoinPoint joinPoint)throws Throwable{
        // System.out.println("aspect is run!!");
        Object[] args = joinPoint.getArgs();
        // 方法签名
        Signature signature1 = joinPoint.getSignature();
        // 获取的是代理类的method对象
        Method method1 = ( (MethodSignature)signature1 ).getMethod();
        // 这个方法才是目标对象上有注解的方法
        Method realMethod = joinPoint.getTarget().getClass().getDeclaredMethod(signature1.getName(), method1.getParameterTypes());
        // 取出对应的注解        
        String name = "";
        int num = -1;
        Annotation[][] parameterAnnotations = realMethod.getParameterAnnotations();
        A: for (Annotation[] annotations : parameterAnnotations) {
            for (Annotation annotation : annotations) {
                //获取注解名
                 name = annotation.annotationType().getSimpleName();
                 num = num + 1;
                 if (name.equals("User")){
                     break A;
                 }
            }
        }

        //获取注解
        //User user = method.getAnnotation(User.class);
        if(name.equals("User")){
            UserVo userVo = (UserVo)args[num];
            if(userVo == null || userVo.getId() == null){
                //未登录需要告诉用户你未登录
                return R.failed("401","请重新获取用户信息!");
            }else {
                //已经登录的继续处理业务
                return joinPoint.proceed(args);
            }
        } else {
            //没有这个注解的不验证登录,继续处理业务
            return joinPoint.proceed(args);
        }
    }

}

  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值