Java 注解annotation+AOP Aspect初使用

作者: 小疯子 分类: Java,Spring Boot 发布时间: 2019-03-26 19:30

一、缘由

简单的在访问一个方法之前需要确认用户已经绑定了手机号,以此写一个注解和aop来实现这个简单的功能

二、代码编写

1. 注解类

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

/**
 * @Author: Xiaofeng
 * @Date: 2019/3/25 9:12
 * @Description: 用户信息完整性验证
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequireUserCompletePermission {

    /** 验证手机号绑定 */
    boolean phone() default false;

}

2.  拦截器处理类

import xxx.RequireUserCompletePermission;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author: Xiaofeng
 * @Date: 2019/3/25 9:19
 * @Description: 用户手机号绑定拦截处理器
 */
@Aspect
@Component
public class RequirePhoneAop {

    // TODO 切面execution留意可能会有更改
    @Pointcut("execution(public * com.fengzi.api.shop..*.controller.*Controller.*(..))")
    public void pointcut() {
    }

    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        RequireUserCompletePermission annotation = method.getAnnotation(RequireUserCompletePermission.class);
        if (annotation == null) {
            return pjp.proceed(pjp.getArgs());
        }
        boolean phone = annotation.phone();
        if (phone && !checkCurrentUserPhoneComplete()) {
            // do check phone
            return ResultUtils.error("用户未绑定手机号");
        }

        // do other information check

        // do proceed
        return pjp.proceed(pjp.getArgs());
    }

    private boolean checkCurrentUserPhoneComplete() {
        MemberBean member = UserUtils.currentMember();
        if (member == null) {
            return false;
        }

        String phone = member.getPhone();
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        return true;
    }

}

3. 注解使用

在Controller的某个方法上调用
@RequireUserCompletePermission( phone = true)
0