需求:
项目中有些模块需要加入工作流审批流程,并且可以选择是否开启工作流。
于是根据需求就想到了用aop做一个通用的模块开关检验。
如果模块没有开启工作流,就直接放行。如果开启了工作流,就启动该模块的工作流流程。
下面上代码
1、首先创建自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ActAnnotation {
//这里是自定义的枚举类
ActModuleEnum key();
}
2、创建切面类
@Component
@Aspect
public class ActAop {
@Autowired
private ActSwitchMapper actSwitchMapper;
@Autowired
private ActProcessMapper actProcessMapper;
@Autowired
private xyr_TaskBiz taskBiz;
/**
* 声明切入点 ActAnnotation注解
*/
@Pointcut(value = "@annotation(com.useeinfo.oa.modules.security.annotation.ActAnnotation)")
public void pointCut() {}
/**
* 对注解的解析 @Around 通过环绕通知来控制业务逻辑
* ProceedingJoinPoint pJoinPoint 目标方法
* ActAnnotation actAnnotation 目标方法的注解对象
*/
@Around("pointCut() && @annotation(actAnnotation)")
public ResultDto around(ProceedingJoinPoint pJoinPoint, ActAnnotation actAnnotation) throws Throwable {
//拿到模块key
ActModuleEnum key = actAnnotation.key();
//检查模块工作流开启状态
Integer moduleStatus = actSwitchMapper.getModuleStatus(key.getCode());
if(moduleStatus != 1){
//模块的工作流开关关闭 直接调用
return (ResultDto)pJoinPoint.proceed();//proceed方法为 不做处理直接调用目标方法
}
//获取该模块运行中的流程数量
int actProcessCount = actProcessMapper.getActProcessCount(key.getCode());
if(actProcessCount < 1){
return ResultUtil.error("该模块没有部署流程或激活流程!如不需要请关闭该模块开关!");
}
//打开了模块开关 并且存在运行中的流程
Object[] args = pJoinPoint.getArgs();
switch (key){
case TASK_RELEASE://任务发布模块
return taskRelease(args,key);
}
return ResultUtil.error("没有调用任何方法");
}
//调用指定方法
private ResultDto taskRelease(Object[] args,ActModuleEnum key){
ResultDto resultDto = taskBiz.realReleaseToAct((Long) args[0]);
return resultDto;
}
}
3、在spring配置文件中启用aop
<aop:aspectj-autoproxy proxy-target-class="true"/>
4、在需要切入的方法上打上自定义注解
@ActAnnotation(key = ActModuleEnum.TASK_RELEASE)
public ResultDto realRelease(Long id){
xyr_Task task = dao.findModel(id);
return this.taskSendMqApp(task);
}