1、maven项目
2、基于ruoyi-fast
3、作业需要: 进入Controller前,将入参userId默认赋值为当前登录用户
4、多个入参是,包含userId的入参实体需位于方法的第一位
5、请求参数,需要定义userId字段,不能定义到父级,没有定义不会报错
二、代码备份1、定义注解
此类,位于common模块
package com.ruoyi.common.annotation;
import java.lang.annotation.*;
/**
* 设值用户ID
* 业务数据,用户级别数据隔离
* 涉及方法: 查询,导出,导入,新增
* @author hgSuper
* @date 2021-08-06
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SetUserId
{
}
2、注解处理-前置通知
package com.ruoyi.framework.aspectj;
import com.ruoyi.common.annotation.SetUserId;
import com.ruoyi.framework.util.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 设值用户ID,设值
* @author hgSuper
* @date 2021-08-06
*/
@Slf4j
@Aspect
@Component
public class SetUserIdAspect
{
// 配置织入点
@Pointcut("@annotation(com.ruoyi.common.annotation.SetUserId)")
public void pointCut()
{
}
/**
* 前置通知 用于拦截操作
* @param joinPoint 切点
*/
@Before("pointCut()")
public void doBefore(JoinPoint joinPoint)
{
handle(joinPoint, null);
}
protected void handle(final JoinPoint joinPoint, final Exception e)
{
try
{
// 获得注解
SetUserId controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null)
{
// 方法没有注解,不处理
return;
}
Object param = joinPoint.getArgs()[0];
Field userIdField = param.getClass().getDeclaredField("userId");
if (null == userIdField) {
// 没有用户ID,不处理
return;
}
userIdField.setAccessible(true);
userIdField.set(param, ShiroUtils.getUserId());
log.info("handle(),设值用户ID,成功,param:{}", param);
}
catch (Exception exp)
{
log.error("handle(),设值用户ID,失败,errMsg:{}", e.getMessage(), e);
}
}
/**
* 是否存在注解,如果存在就获取
*/
private SetUserId getAnnotationLog(JoinPoint joinPoint) throws Exception
{
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null)
{
return method.getAnnotation(SetUserId.class);
}
return null;
}
}
3、注解使用-示例图
此类位于,admin模块