自定义注解
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface HasRole {
String[] value();
String flag() default "or";
String msg() default "权限不足";
}
AOP
@Aspect
@EnableAspectJAutoProxy
@Slf4j
@Component
public class RoleAspect {
@Around("execution(* com.entor.controller.*.*(..))")
public Object round(ProceedingJoinPoint joinPoint) throws Throwable {
String name = joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
log.info("当前系统时间:" + new Date() + "开始执行的方法" + name + ",方法参数:" + Arrays.toString(args));
long start = System.currentTimeMillis();
Object proceed = joinPoint.proceed();
long end = System.currentTimeMillis();
log.info("结束执行方法:" + name + ",方法执行时间:" + (end - start) + "毫秒");
log.info("方法的返回值:"+proceed);
return proceed;
}
@Before("@annotation(hasRole)")
public void checkRole(JoinPoint joinPoint, HasRole hasRole) {
Signature signature = joinPoint.getSignature();
log.info("方法名称:" + signature.getName());
log.info("连接点对象:" + signature);
Object[] args = joinPoint.getArgs();
log.info("方法参数:" + Arrays.deepToString(args));
log.info("目标对象:" + joinPoint.getTarget());
String flag = hasRole.flag();
log.info("flag:" + flag);
String msg = hasRole.msg();
log.info("flag:" + msg);
String[] value = hasRole.value();
log.info(Arrays.toString(value));
String role = "admin";
if (flag == null || flag.equals("or")) {
if (!Arrays.asList(value).contains(role)) {
throw new RuntimeException(msg);
}
} else {
if (!check(new String[]{role}, value)) {
throw new RuntimeException(msg);
}
}
}
public boolean check(String[] ownRoles, String[] requireRoles) {
if (ownRoles.length < requireRoles.length) {
return false;
}
HashSet<String> ownRolesSet = new HashSet<>(Arrays.asList(ownRoles));
HashSet<String> requireRolesSet = new HashSet<>(Arrays.asList(requireRoles));
List<String> list = ownRolesSet.stream().filter(ownRole -> requireRolesSet.contains(ownRole)).collect(Collectors.toList());
return list.size() == requireRolesSet.size();
}
}
使用注解和AOP注入通知
public interface UserMapper {
@Insert("insert into user(age,password,sex,username)values(#{age},#{password},#{sex},#{username})")
@HasRole(value = {"admin","user"},flag = "or")
int save(User user);
}