1.首先定义一个注解类,
package com.qpyx.common.annotation;
import java.lang.annotation.*;
/**
* @ClassName: GameUser
* @Description: 游戏用户权限拦截
* @Author: song
* @Date: 2022/04/07
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GameUser {
/**
* 方法类型
*/
public String methodType() default "";
}
2.从方法上获取这个注解,配置这个注解的织入点,方法或者类前后的你需要编写的逻辑
package com.qpyx.framework.aspectj; import com.qpyx.common.annotation.GameUser; import com.qpyx.common.utils.SecurityUtils; import com.qpyx.common.utils.StringUtils; import com.qpyx.common.utils.exception.UtilException; import com.qpyx.framework.config.RequestDataHelper; import com.qpyx.game.entity.MGame; import com.qpyx.game.service.MGameService; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import java.lang.reflect.Method; /** * @author SongJiaHao * @Date: 2022/4/7 11:26 * @Description:用于运营管理用户对游戏的删除,编辑,新增操作的权限判断 */ @Order(1) @Aspect @Component public class GameAndUserAspect { @Autowired private MGameService mGameService; /** * 配置织入点 */ @Pointcut("execution(* com.qpyx.*..service..*.*(..))") public void GameAndUserPointCut() { } /** *方法前执行的前执行的方法 */ @Before("GameAndUserPointCut()") public void before(JoinPoint joinPoint){ RequestDataHelper.clearRequestData(); //获得注解 GameUser gameUser = getAnnotation(joinPoint); if(gameUser==null){ return; } //获取参数 Object[] args = joinPoint.getArgs(); //1.获得当前在操作这个游戏的id String gameId=(String)args[0]; //2.从游戏列表中获取这个游戏 MGame mGame = mGameService.selectGameById(gameId); //3.获取当前用户的id String userId = SecurityUtils.getLoginUser().getUser().getUserId(); //4.判空 if(StringUtils.isNull(mGame.getPrincipal())||StringUtils.isNull(mGame.getPrincipal())){ UtilException utilException = new UtilException("抱歉,这个游戏还未添加指定负责人和审核人"); throw utilException; } //5.用户id和这个游戏的负责人id或则产品经理的id不相等,抛出异常 if(!(userId.equals(mGame.getPrincipal().toString())||userId.equals(mGame.getProductDirector().toString()))){ UtilException utilException = new UtilException("抱歉,您仅有这个游戏的查看的权限"); throw utilException; } } /** * 是否存在注解,如果存在就获取 */ private GameUser getAnnotation(JoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; //先获取类上面的注解 Class cls = methodSignature.getDeclaringType(); boolean isNoCheckAuth = cls.isAnnotationPresent(GameUser.class); if(isNoCheckAuth){ //类名前注解 return (GameUser) cls.getAnnotation(GameUser.class); } //如果类上面没有,就获取方法上面的注解 Method method = methodSignature.getMethod(); if (method != null) { return method.getAnnotation(GameUser.class); } //如果都没有,则返回null return null; } }