例子1:只使用注解不传入参数
1.自定义注解类
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
@Component
public @interface DataLimited {
}
2.使用切面,对使用了注解的方法进行业务处理
@Order(1)
@Component
@Aspect
public class DataLimitedAspect {
@Resource
private UserService userService;
@Pointcut("@annotation(org.example.bilili.annotation.DataLimited)")
public void check(){
}
@Before("check()")
public void doBefore(JoinPoint joinPoint){
int userId = userService.getCurrentUserId();
//实际需要从DB中获取
List<String> dbRoleCodeList = Arrays.asList("role1", "role2", "role3");
Set<String> dbRoleCodeSet = dbRoleCodeList.stream().collect(Collectors.toSet());
//获取方法中使用的参数
Object[] args = joinPoint.getArgs();
for (Object arg:args){
if(arg instanceof GoodsSearchForm){
GoodsSearchForm goodsSearchForm = (GoodsSearchForm)arg ;
String type = goodsSearchForm.getType();
if(dbRoleCodeSet.contains("role2") && "0".equals(type)){
throw new BusinessException("参数异常");
}
}
}
}
}
3.注解的使用,调用test3这个方法,需要有role2这个角色并且输入参数type=0
@DataLimited
@GetMapping("/test3")
public CommonResponse<String> test3(@RequestBody GoodsSearchForm goodsSearchForm) {
return CommonResponse.success("test3");
}
例子2:使用注解并且注解传入参数
1.自定义注解类
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
@Component
public @interface ApiLimitedRole {
String[] limitedRoleCodeList() default {};
}
2.使用切面,对使用了注解的方法进行业务处理
@Order(1)
@Component
@Aspect
public class ApiLimitedRoleAspect {
@Resource
private UserService userService;
@Pointcut("@annotation(org.example.bilili.annotation.ApiLimitedRole)")
public void check(){
}
@Before("check() && @annotation(apiLimitedRole)")
public void doBefore(JoinPoint joinPoint, ApiLimitedRole apiLimitedRole){
int userId = userService.getCurrentUserId();
String[] limitedRoleCodeList = apiLimitedRole.limitedRoleCodeList();
Set<String> limitedRoleCodeSet = Arrays.stream(limitedRoleCodeList).collect(Collectors.toSet());
//实际需要从DB中获取
List<String> dbRoleCodeList = Arrays.asList("role1", "role2", "role3");
Set<String> dbRoleCodeSet = dbRoleCodeList.stream().collect(Collectors.toSet());
//取交集
dbRoleCodeSet.retainAll(limitedRoleCodeSet);
if(CollectionUtils.isEmpty(dbRoleCodeSet)){
throw new BusinessException("权限不足");
}
}
}
3.注解的使用,调用test2这个方法,limitedRoleCodeList 传入role6,业务中需要role1,role2,role3
这三个其中一个角色,传入的是role6,不满足条件,会报错
//role6没有权限 会报错
@ApiLimitedRole(limitedRoleCodeList = {"role6"})
@GetMapping("/test2")
public CommonResponse<String> test2() {
return CommonResponse.success("test2");
}