1. 自定义注解
package com.yuhuofei.annotation;
import java.lang.annotation.*;
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginStatusCheck {
String value() default "";
}
2. 定义切面
package com.yuhuofei.annotation;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
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.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@Component
@Slf4j
@Aspect
public class LoginStatusCheckAspect {
@Resource
private UserInfoMapper userInfoMapper;
@Pointcut("@annotation(com.yuhuofei.annotation.LoginStatusCheck)")
public void checkLoginStatus() {
}
@Around("checkLoginStatus()")
public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
log.info("获取的参数是:{}", args);
Class<?> aClass = args[0].getClass();
Field field = aClass.getDeclaredField("userName");
String name = field.getName();
log.info("属性是:{}", name);
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), aClass);
Method getMethod = pd.getReadMethod();
Object invoke = getMethod.invoke(args[0]);
log.info("userName的值是:{}", invoke);
String methodName = joinPoint.getSignature().getName();
UserInfoDO userInfoDo = userInfoMapper.selectOne(new QueryWrapper<UserInfoDO>()
.eq("delete_flag", false)
.eq("user_name", invoke.toString()));
if (null == userInfoDo) {
throw new Exception("登录失效,请重新登录!");
}
return joinPoint.proceed();
}
}
3. 使 用
package com.yuhuofei.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import com.yuhuofei.annotation.LoginStatusCheck;
@Slf4j
@RestController
@RequestMapping("/data")
public class DataController {
@Autowired
private DataService dataService;
@LoginStatusCheck(value = "数据列表接口")
@PostMapping("/data-list")
public String queryData(){
log.info("调用数据列表接口");
result = dataService.hanList();
return result;
}
}