SpringBoot2.x集成Activili7工作流

准备工作

安装actiBPM插件, 此插件在idea2020版本已经在市场搜不到了, 必须通过连接去下载下来本地安装了
https://wws.lanzoui.com/i2CI0p60yxi
密码:9htv

搭建springboot项目

这里需要注意的是,springboot的版本对activili的版本兼容都不太友善, 比如我之前建的是2.2.6, 用的activili版本是7.1.0.M6,后来我把springboot降级到2.0.3, 他就启动不了了

引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhbcm</groupId>
    <artifactId>bmp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>bmp</name>
    <description>工作流</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <!-- 阿里 druid 数据源 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
            <scope>compile</scope>
        </dependency>

        <!-- activitu+springboot集成的jar-->
        <dependency>
            <groupId>org.activiti</groupId>
            <artifactId>activiti-spring-boot-starter</artifactId>
            <!--<version>7.1.0.M6</version>-->
        </dependency>

        <!-- 流程图-->
        <!--<dependency>-->
        <!--    <groupId>org.activiti</groupId>-->
        <!--    <artifactId>activiti-diagram-rest</artifactId>-->
        <!--    <version>5.23.0</version>-->
        <!--</dependency>-->

        <!-- mybatis+springboot的jar-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
            <scope>runtime</scope>
        </dependency>

        <!--整合springboot与junit测试依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.activiti.cloud.dependencies</groupId>
                <artifactId>activiti-cloud-dependencies</artifactId>
                <version>7.0.0.Beta3</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

高版本入门: https://blog.csdn.net/weixin_43963583/article/details/105831198 (但是他实际上也就做了做准备工作, 里面的那个链接也没啥用, 还是用我上面的版本吧)

文件配置

spring:
  #Activiti property configuration
  activiti:
    database-schema-update: true
    history-level: full
    db-history-used: true

  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    platform: mysql
    url: jdbc:mysql://localhost:3306/activity?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
    username: root
    password: 123456
    druid:
      initialSize: 5
      minIdle: 5
      maxActive: 20
      maxWait: 60000
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      filters: stat,wall,log4j
      filter:
        stat:
          log-slow-sql: true
server:
  port: 7777

项目结构

在这里插入图片描述

添加基本配置

ActivitiConfig

import org.activiti.engine.*;
import org.activiti.engine.impl.cfg.StandaloneProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * https://blog.csdn.net/weixin_45982841/article/details/115673862?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-1&spm=1001.2101.3001.4242
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/5/14 0:46
 */
@Configuration
public class ActivitiConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public StandaloneProcessEngineConfiguration standaloneProcessEngineConfiguration() {
        StandaloneProcessEngineConfiguration processEngineConfiguration = new StandaloneProcessEngineConfiguration();
        processEngineConfiguration.setDataSource(dataSource);
        processEngineConfiguration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
        processEngineConfiguration.setAsyncExecutorActivate(false);
        return processEngineConfiguration;
    }

    @Bean
    @Primary
    public ProcessEngine buildProcessEngine() {
        return standaloneProcessEngineConfiguration().buildProcessEngine();
    }

    @Bean
    public RepositoryService repositoryService() {
        return buildProcessEngine().getRepositoryService();
    }

    @Bean
    public RuntimeService runtimeService() {
        return buildProcessEngine().getRuntimeService();
    }

    @Bean
    public TaskService taskService() {
        return buildProcessEngine().getTaskService();
    }

    @Bean
    public HistoryService historyService() {
        return buildProcessEngine().getHistoryService();
    }
}

WorkFlowConfig

import com.google.common.collect.ImmutableList;
import org.activiti.api.runtime.shared.identity.UserGroupManager;
import org.activiti.engine.impl.history.HistoryLevel;
import org.activiti.spring.SpringAsyncExecutor;
import org.activiti.spring.SpringProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.List;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2021/5/14 0:47
 */
@Configuration
public class WorkFlowConfig {

    @Autowired
    private DataSource dataSource;

    //高版本需要手动填写,所以需要显示声明,并且交个Spring维护和管理。
    @Primary
    @Bean
    public UserGroupManager userGroupManager() {
        return new UserGroupManager() {
            @Override
            public List<String> getUserGroups(String s) {
                return ImmutableList.of("指定用户归属组");
            }

            @Override
            public List<String> getUserRoles(String s) {
                return null;
            }

            @Override
            public List<String> getGroups() {
                return null;
            }

            @Override
            public List<String> getUsers() {
                return null;
            }
        };
    }

    @Bean
    public SpringProcessEngineConfiguration springProcessEngineConfiguration(PlatformTransactionManager transactionManager) {
        SpringProcessEngineConfiguration springProcessEngineConfiguration = new SpringProcessEngineConfiguration();
        springProcessEngineConfiguration.setDataSource(dataSource);
        springProcessEngineConfiguration.setTransactionManager(transactionManager);
        SpringAsyncExecutor springAsyncExecutor = new SpringAsyncExecutor();
        springAsyncExecutor.setTaskExecutor(threadPoolTaskExecutor());
        springProcessEngineConfiguration.setAsyncExecutor(springAsyncExecutor);
        springProcessEngineConfiguration.setDatabaseSchemaUpdate("true");
        springProcessEngineConfiguration.setUserGroupManager(userGroupManager());
        springProcessEngineConfiguration.setHistoryLevel(HistoryLevel.FULL);
        springProcessEngineConfiguration.setDbHistoryUsed(true);
        return springProcessEngineConfiguration;
    }

    @Primary
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(10);
        threadPoolTaskExecutor.setMaxPoolSize(30);
        threadPoolTaskExecutor.setKeepAliveSeconds(500);
        threadPoolTaskExecutor.setQueueCapacity(500);
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}

开始画流程图

在resources目录下建一个文件夹

我建了个processes
右击文件夹开始创建
在这里插入图片描述
在这里插入图片描述
如上图画完之后, 按shift+F6改个名字XX_bpmn20.xml, 为什么要用bpmn20.xml后缀我也不太明白, 但我没用这个结尾报了no processes deployed with key ‘xxxx’

导出png图片

这个时候你的xml是这样的
在这里插入图片描述
点击下方的desinger,导出来png放在xml同级位置
在这里插入图片描述

<userTask activiti:assignee="${student}" activiti:exclusive="true" id="_3" name="学生填写申请表"/>
<userTask activiti:assignee="${teacher}" activiti:exclusive="true" id="_4" name="班主任审批"/>

两个任务需要这样配置
到这里前期准备工作就算是做完了

其实这个时候你启动一下的话, 可能会报文件找不到
https://blog.csdn.net/weixin_37380784/article/details/99410559
我照着这篇文章操作了一下, 发现没用还把test弄得不能用了就复原了, 然后再启动发现就能找到文件了, 这个很神奇!

代码

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {BmpApplication.class})
//配置启动类
public class BmpApplicationTests
{
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    public final String PROCESS_DEFINITION_KEY = "myProcess_1";

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    /**
     * 部署流程
     */
    @Test
    public void prepare()
    {
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("processes/test_bpmn20.xml")//添加bpmn资源
                .addClasspathResource("processes/test.png")
                .name("请假申请单流程")
                .deploy();
        log.info("流程部署id:" + deployment.getName());
        log.info("流程部署名称:" + deployment.getId());
    }

    /**
     * 启动流程实例
     */
    @Test
    public void startProcess()
    {
        Map<String, Object> map = new HashMap<>();
        //使用UEL 表达式设置
        // 学生填写申请单    Assignee:${student}
        map.put("student", "lucy");
        // 班主任审批    Assignee:${teacher}
        map.put("teacher", "jack");
        ProcessInstance instance = runtimeService.startProcessInstanceByKey(PROCESS_DEFINITION_KEY, map);
        System.out.println("流程实例ID:" + instance.getId());
        System.out.println("流程定义ID:" + instance.getProcessDefinitionId());
    }

    /**
     * 任务查询
     */
    @Test
    public void searchTask()
    {
        //流程启动后,各各任务的负责人就可以查询自己当前需要处理的任务,查询出来的任务都是该用户的待办任务。
        List<Task> list = taskService.createTaskQuery()
                //流程实例key
                .processDefinitionKey(PROCESS_DEFINITION_KEY)
                //查询谁的任务
                //.taskAssignee("")
                .list();
        // List<String> idList = new ArrayList<String>();

        for (Task task : list)
        {
            // idList.add (task.getId ());
            System.out.println("任务ID:" + task.getId());
            System.out.println("任务名称:" + task.getName());
            System.out.println("任务的创建时间:" + task.getCreateTime());
            System.out.println("任务的办理人:" + task.getAssignee());
            System.out.println("流程实例ID:" + task.getProcessInstanceId());
            System.out.println("执行对象ID:" + task.getExecutionId());
            System.out.println("流程定义ID:" + task.getProcessDefinitionId());
        }
        // return idList;
    }
}

由于暂时项目中还不需要集成, 所以我这里只是基本学习, 没有项目实战, 后续使用会补上新文章, thank you~~~

参考文章

快速使用IDEA搭建SpringBoot项目,集成Activiti7(一)
activiti部署报错 resource '*‘.bpmn’not found
IDEA上SpringBoot2.x集成activiti7以及基本使用

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值