Flowable全局监听器,另一种实现

1,469 阅读1分钟

前言:

该本章是Flowable全局监听 的另一种实现方法,黑猫白猫能抓到老鼠就是好猫~

实际需求举例:

比如下一个节点是 用户A去审批,甲方要求系统主动发消息通知用户A去审批,你又不可能为每个节点都设置监听器,那就需要全局监听器来实现了

实现步骤

(1)新建全局监听器配置类

监听级别为 TASK_CREATED(任务创建时触发),自己根据实际需要配置对应级别

`


import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.engine.RuntimeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @author 勤任风
 * @date 2021-09-29 17:29
 * 全局监听器配置
 */
@Slf4j
@Component
@Configuration
public class InitConfig implements CommandLineRunner {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private FlowableBaseEventListenerImpl flowableBaseEventListener;// 你的全局监听器实现

    @Override
    public void run(String... args) {
       //配置监听器,监听级别为 TASK_CREATED
       runtimeService.addEventListener(flowableBaseEventListener,FlowableEngineEventType.TASK_CREATED);
        System.out.println("全局任务监听器配置:"+flowableBaseEventListener);
    }

}

`

(2)全局监听器实现

`


import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.cfg.TransactionState;
import org.flowable.common.engine.impl.event.FlowableEntityEventImpl;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;
import java.util.Set;

/**
 * @author 勤任风
 * @date 2021-09-29 17:29
 * 全局监听器,逻辑实现
 */
@Component
@Slf4j
public class FlowableBaseEventListenerImpl implements FlowableEventListener {

    // 写你的监听逻辑,即要执行的内容
    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        //获取节点内容
        TaskEntity taskEntity = (TaskEntity) ((FlowableEntityEventImpl) flowableEvent).getEntity(); 
        //获取审批候选人(即谁来审批)
        Set<IdentityLink> candidates = taskEntity.getCandidates();
        //获取流程名称
        String currentProcess = taskEntity.getName(); 
        // TODO 你的业务逻辑

    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        //事务提交后触发
        return TransactionState.COMMITTED.name();
    }
}

`