业务需求:对接口增加权限验证功能
首先引入jar包
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
自定义注解
import java.lang.annotation.*;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface VerifyAuthority {
VerifyAuthorityElement value() default VerifyAuthorityElement.DGRB;
}
//配置枚举元素
public enum VerifyAuthorityElement {
DGRB;
//后续继续添加
}
看些接口如何配置:
@RestController
@RequestMapping("dgrb")
@Slf4j
public class SendMessageController {
@PostMapping("sendMessage")
@VerifyAuthority(value = VerifyAuthorityElement.DGRB)
public Result sendMessage(@RequestBody Map<String, Object> paramMap) {
//接口处理逻辑
}
}
切面如何写呢
import com.xx.dgrb.dao.SystemSettingsDao;
import com.xx.dgrb.model.Result;
import com.xx.dgrb.model.SystemSettings;
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.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
@Slf4j
@Aspect
public class VerifyAuthorityHandler {
@Autowired
private SystemSettingsDao systemSettingsDao;
@Autowired
private DgrbHandler dgrbHandler;
//指定这个注解,做切面
@Pointcut("@annotation(com.xx.yy.apsect.VerifyAuthority) ")
public void pointCut() {
}
@Around("pointCut()")
public Object handle(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//获取注解
VerifyAuthority dgrb = methodSignature.getMethod().getAnnotation(VerifyAuthority.class);
Object[] args = joinPoint.getArgs();
//获取入参
Map<String, Object> paramMap = (Map<String, Object>) args[0];
//如果注解里面的值是我设置的话,这里写需要增加的逻辑
if (VerifyAuthorityElement.DGRB.equals(dgrb.value())) {
......
}
//返回主流程,让他继续执行
return joinPoint.proceed();
//因为用的around,所以在 joinPoint.proceed()执行完,还可以增加处理逻辑的
}
}