Java 通过自定义注解实现AOP面向切面编程

自定义注解:

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

@Target(ElementType.METHOD)
public @interface TestOverdue {
    String value() default "";
}

controller:

/**
     * 登录
     */
    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping("/sys/login")
    @TestOverdue
    public CommonResult login(@RequestBody SysLoginForm form) {
    	Map<String, Object> params = new HashMap<>();
    	......
        params.put("token", token);
        params.put("expire", expire);
        params.put("username", loginUser.getName());
        params.put("id",loginUser.getId());
        params.put("departmentId",loginUser.getDepartmentId());
        params.put("days",form.getDays());
        return CommonResult.ok().data(params);
   }

切面类:

import com.his.common.result.CommonResult;
import com.his.system.shiro.form.SysLoginForm;
import com.his.uc.facade.ISettingFacade;
import org.apache.dubbo.config.annotation.Reference;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Component
@Aspect
public class APIProxy {

    @Reference
    private ISettingFacade iSettingFacade;

    //定义切点
    @Pointcut("@annotation(com.his.system.aspect.TestOverdue)")
    public void doAspect() {
    }

    // 环绕通知
    @Around("doAspect()")
    public Object around(ProceedingJoinPoint  joinPoint) throws Throwable {
        Map setting = iSettingFacade.getById();
        String expireTime = setting.get("expireTime").toString();

        SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        /*天数差*/
        Date fromDate1 = simpleFormat.parse(expireTime);
        Date toDate1 = new Date();
        long from1 = fromDate1.getTime();
        long to1 = toDate1.getTime();
        int days = (int) ((from1 - to1) / (1000 * 60 * 60 * 24));
        System.out.println("两个时间之间的天数差为:" + days);
        Object proceed;
        if(days <= 0){
        	//①-直接返回失败的内容
            proceed = CommonResult.loginError().msg("已过期,不可使用!");
        }else if(days <= 30 && days > 0){
        	//②-弹框提示到期时间后可继续登陆成功
        	//获取目标参数
            Object[] args1 = joinPoint.getArgs();
            //强转为需要的对象
            SysLoginForm sysLoginForm = (SysLoginForm)args1[0];
            //将当前计算天数需返回到login接口返回成功的map中
            sysLoginForm.setDays(days);
            args1[0] = sysLoginForm;
            proceed = joinPoint.proceed(args1);
        }else {
        	//③-继续执行目标方法
            proceed = joinPoint.proceed();
        }
        return proceed;
    }

}

你可能感兴趣的:(aop)