1、自我理解
aop(面向切面编程)相信大家多少有些了解,而基于aop实现的自定义注解功能类似,注解在切面编程过程中起到类似一个开关作用,它可以让某个方法(METHOD类型注解)灵活开启拦截的一些功能,例如调用此方法时是否权限校验、是否业务检查等等,下面开始一个简单的demo
2、定义一个在方法上使用的注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author: lizj
* @CreateTime: 2024-02-05 14:46
* @Description: TODO
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Check {
String[] params() default {};
}
3、创建一个AOP拦截类,主要是拦截此注解,用于一些业务检查
import com.ccse.semiphysical.mapper.EnvironmentApiMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import java.util.List;
/**
* @Author: lizj
* @CreateTime: 2024-02-05 14:48
* @Description: TODO
*/
@Aspect
@Component
@Slf4j
public class CheckValidateAspect {
@Autowired
EnvironmentApiMapper environmentApiMapper;
@Value("${datasource-primary.dbname}")
private String dbName;
@Before("@annotation(com.ccse.semiphysical.common.anotation.Check)")
public void checkIntercept( JoinPoint joinPoint) throws Exception {
Signature signature = joinPoint.getSignature();
String name = signature.getName();
Object[] args = joinPoint.getArgs();
if (ObjectUtils.isEmpty(args)){
throw new Exception("入参不允许为空,请检查");
}
if ("shutdown".equals(name)){
List<String> tableNames = (List<String>) args[0];
if (CollectionUtils.isEmpty(tableNames)){
throw new Exception("场景表的集合不允许为空");
}
for (Object tableName : tableNames) {
if (ObjectUtils.isEmpty(tableName)){
throw new Exception("集合中场景表名不允许为空");
}
String tableNameValue = environmentApiMapper.getTableName(tableName.toString(), dbName);
if (ObjectUtils.isEmpty(tableNameValue)){
throw new Exception("当前数据库"+dbName+"中不存在"+tableName+"数据表,无法做导出CSV操作,请检查");
}
}
}
}
}
4、注解使用
@Check()
@PostMapping("shutdown")
public R shutdown(@RequestBody List<String> params) throws Exception {
boolean shutdown = environmentApiService.shutdown(params);
if (shutdown) {
return R.ok("场景停止成功");
}else {
return R.fail("场景停止失败");
}
}
5、调用效果
可以看出检查成功并且可以看到拦截方法中抛出的异常