(二)springboot整合activiti7

activit和springboot都会不断的更新,网络上那么多教程,经常不说清楚版本的问题,浪费很多时间。
我参考官网的文档,选定了activiti7.1.0-M7,springboot2.1.13.RELEASE;
但是发现7.1.0-M7太新了,还没有相应的starter,就降低一下用7.1.0-M6


image.png

1.准备环境

创建一个新的项目或者Module,先修改pom文件

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.1.13.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.activiti/activiti-spring-boot-starter -->
    <dependency>
        <groupId>org.activiti</groupId>
        <artifactId>activiti-spring-boot-starter</artifactId>
        <version>7.1.0.M6</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.45</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

然后,添加application.yml文件

    server:
      port: 8085
    spring:
      application:
        name: spring-activiti
      datasource:
        url: jdbc:mysql://localhost:3306/activiti7?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&nullCatalogMeansCurrent=true
        username: root
        password: password
        driver-class-name: com.mysql.jdbc.Driver
      activiti:
        #1.flase: 默认值。activiti在启动时,会对比数据库表中保存的版本,如果没有表或者版本不匹配,将抛出异常
        #2.true: activiti会对数据库中所有表进行更新操作。如果表不存在,则自动创建
        #3.create_drop: 在activiti启动时创建表,在关闭时删除表(必须手动关闭引擎,才能删除表)
        #4.drop-create: 在activiti启动时删除原来的旧表,然后在创建新表(不需要手动关闭引擎)
        database-schema-update: true
        #检测历史表是否存在
        db-history-used: true
        #记录历史等级 可配置的历史级别有none, activity, audit, full
        history-level: full
        #校验流程文件,默认校验resources下的processes文件夹里的流程文件
        check-process-definitions: false

在resources下创建processes文件夹用于存放审批流程文件;

2.安装actiBPM插件

访问https://plugins.jetbrains.com/,下载actiBPM.jar
File->settings->plugins从本地磁盘安装;

image.png

3.创建第一个流程文件

image.png
image.png

注意这个流程的名字叫myProcess_leave;
TeamLeader审核可以指明由谁审核,这里用的是String;
assginee是指定某个人处理;
cadidate是几个人都可以处理,处理前要先认领一下,claim;

4.添加config文件、util、controller、test

4.1.config文件这里初始化了一些账号

package com.lbc.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Configuration
@EnableWebSecurity
public class DemoApplicationConfiguration extends WebSecurityConfigurerAdapter {

private Logger logger = LoggerFactory.getLogger(DemoApplicationConfiguration.class);

@Override
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(myUserDetailsService());
}

@Bean
public UserDetailsService myUserDetailsService() {

    InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();

    String[][] usersGroupsAndRoles = {
            {"user", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
            {"team-leader", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
            {"hr", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
            {"other", "password", "ROLE_ACTIVITI_USER", "GROUP_otherTeam"},
            {"admin", "password", "ROLE_ACTIVITI_ADMIN"},
    };

    for (String[] user : usersGroupsAndRoles) {
        List<String> authoritiesStrings = Arrays.asList(Arrays.copyOfRange(user, 2, user.length));
        logger.info("> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]");
        inMemoryUserDetailsManager.createUser(new User(user[0], passwordEncoder().encode(user[1]),
                authoritiesStrings.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList())));
    }
    return inMemoryUserDetailsManager;
}


@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .authorizeRequests()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

}

4.2.SecurityUtil 这是一个工具类,主要是为了方便模拟SpringSecurity的用户登录。

package com.lbc.demo.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;

@Component
public class SecurityUtil {

@Resource
private UserDetailsService userDetailsService;

public void logInAs(String username) {

    UserDetails user = userDetailsService.loadUserByUsername(username);
    if (user == null) {
        throw new IllegalStateException("User " + username + " doesn't exist, please provide a valid user");
    }

    SecurityContextHolder.setContext(new SecurityContextImpl(new Authentication() {
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            return user.getAuthorities();
        }

        @Override
        public Object getCredentials() {
            return user.getPassword();
        }

        @Override
        public Object getDetails() {
            return user;
        }

        @Override
        public Object getPrincipal() {
            return user;
        }

        @Override
        public boolean isAuthenticated() {
            return true;
        }

        @Override
        public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        }

        @Override
        public String getName() {
            return user.getUsername();
        }
    }));
    org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(username);
}

}

4.3. Controller里面写了几个流程操作的例子

package com.lbc.demo.controller;

import com.lbc.demo.utils.SecurityUtil;
import org.activiti.api.process.model.ProcessDefinition;
import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/activiti")
public class ActivitiController {
@Resource
private ProcessRuntime processRuntime;
@Resource
private TaskRuntime taskRuntime;
@Resource
private SecurityUtil securityUtil;
@Autowired
private ProcessEngine processEngine;


/**
 * 根据bpmn文件部署一个流程
 *
 * @return
 */
@RequestMapping("/createDeploy")
public Deployment createDeploy() {
    RepositoryService repositoryService = processEngine.getRepositoryService();

    Deployment deployment = repositoryService.createDeployment()
            .addClasspathResource("processes/leave-approve.bpmn")//添加bpmn资源
//                .addClasspathResource("diagram/holiday.png")
            .name("请假申请单流程")
            .deploy();

    System.out.println("流程部署id:" + deployment.getName());
    System.out.println("流程部署名称:" + deployment.getId());
    return deployment;
}

/**
 * 查询已经部署的流程
 */
@RequestMapping("/getProcess")
public void getProcess() {
    //查询所有流程定义信息
    Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 10));
    System.out.println("当前流程定义的数量:" + processDefinitionPage.getTotalItems());
    //获取流程信息
    for (ProcessDefinition processDefinition : processDefinitionPage.getContent()) {
        System.out.println("流程定义信息" + processDefinition);
    }
}


/**
 * 启动流程示例
 */
@RequestMapping("/startInstance")
public void startInstance() {
    ProcessInstance instance = processRuntime.start(ProcessPayloadBuilder.start().withProcessDefinitionKey("myProcess_leave_approve_1").build());
    System.out.println(instance.getId());
}

/**
 * 获取任务,拾取任务,并且执行(认领、完成)
 */
@RequestMapping("/getTask")
public void getTask() {
    securityUtil.logInAs("team-leader");        //指定组内任务人
    Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, 10));
    if (tasks.getTotalItems() > 0) {
        for (Task task : tasks.getContent()) {
            System.out.println("任务名称:" + task.getName());
            //拾取任务
            taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
            //执行任务
            taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId()).build());
        }
    }
}

}

4.4. test里面也是流程操作的例子

package com.lbc.demo;

import com.lbc.demo.utils.SecurityUtil;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ActivitiTest {
@Resource
private RepositoryService repositoryService;
@Resource
private TaskService taskService;
@Resource
private RuntimeService runtimeService;
@Resource
private HistoryService historyService;
@Resource
private ProcessRuntime processRuntime;
@Autowired
private TaskRuntime taskRuntime;
@Resource
private SecurityUtil securityUtil;

/**
 * 根据bpmn文件,创建一个新的流程
 */
@Test
public void create() {
    Deployment deployment = repositoryService.createDeployment()
            .addClasspathResource("processes/leave-approve.bpmn")//添加bpmn资源
//                .addClasspathResource("diagram/holiday.png")
            .name("请假申请单流程")
            .deploy();

    System.out.println("流程部署id:" + deployment.getId());
    System.out.println("流程部署名称:" + deployment.getName());
}

/**
 * 查询已有的流程
 */
@Test
public void read() {
    List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().list();
    for (ProcessDefinition p : processDefinitions) {
        System.out.println(p.getDeploymentId());
        System.out.println(p);
    }
}

/**
 * 删除已有的流程
 */
@Test
public void delete() {
    //这个id是DeploymentId
    repositoryService.deleteDeployment("6c41300f-aee0-11ea-9969-00ff0d0b7f9d");

    List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery().list();
    for (ProcessDefinition p : processDefinitions) {
        System.out.println("DeploymentId:" + p.getDeploymentId());
        System.out.println(p);
    }
}

/**
 * 启动一个实例
 */
@Test
public void startProcessInstance() {
    System.out.println("Number of process instances: " + runtimeService.createProcessInstanceQuery().count());
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("myProcess_leave");
    System.out.println("Number of process instances: " + runtimeService.createProcessInstanceQuery().count());

}

/**
 * 传递参数、读取参数
 * 查询用户的任务列表
 */
@Test
public void taskQuery() {
    //根据流程定义的key,负责人assignee来实现当前用户的任务列表查询
    List<Task> list = taskService.createTaskQuery()
            .processDefinitionKey("myProcess_leave")
            .taskCandidateOrAssigned("teamleader")
            .list();

    if (list != null && list.size() > 0) {

        for (Task task : list) {
            Map<String, Object> variables = new HashMap<String, Object>();
            variables.put("employeeName", "Kermit");
            variables.put("numberOfDays", new Integer(4));
            variables.put("vacationMotivation", "I'm really tired!");

            taskService.setVariable(task.getId(), "参数", variables);
        }

        for (Task task : list) {
            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());
            System.out.println("getOwner:" + task.getOwner());
            System.out.println("getCategory:" + task.getCategory());
            System.out.println("getDescription:" + task.getDescription());
            System.out.println("getFormKey:" + task.getFormKey());

            Map<String, Object> map1 = (Map<String, Object>) taskService.getVariable(task.getId(), "参数");
            for (Map.Entry<String, Object> m : map1.entrySet()) {
                System.out.println("key:" + m.getKey() + " value:" + m.getValue());
            }
            Map<String, Object> map = task.getProcessVariables();
            for (Map.Entry<String, Object> m : map.entrySet()) {
                System.out.println("key:" + m.getKey() + " value:" + m.getValue());
            }
            for (Map.Entry<String, Object> m : task.getTaskLocalVariables().entrySet()) {
                System.out.println("key:" + m.getKey() + " value:" + m.getValue());
            }

        }
    }
}

/**
 * 完成任务
 */
@Test
public void completeTask() {
    securityUtil.logInAs("teamleader");        //指定组内任务人
    Page<org.activiti.api.task.model.Task> tasks = taskRuntime.tasks(Pageable.of(0, 10));
    if (tasks.getTotalItems() > 0) {
        for (org.activiti.api.task.model.Task task : tasks.getContent()) {
            System.out.println("任务名称:" + task.getName());
            //拾取任务
            taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
            //执行任务
            taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId()).build());
        }
    }
}

/**
 * 历史活动实例查询,参数也能查到
 */
@Test
public void queryHistoryTask() {
    List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery() // 创建历史活动实例查询
//                .processInstanceId("9671cdea-3367-11ea-a057-30b49ec7161f") // 执行流程实例id
            .includeProcessVariables()
            .orderByTaskCreateTime()
            .asc()
            .list();
    for (HistoricTaskInstance hai : list) {
        System.out.println("活动ID:" + hai.getId());
        System.out.println("流程实例ID:" + hai.getProcessInstanceId());
        System.out.println("活动名称:" + hai.getName());
        System.out.println("办理人:" + hai.getAssignee());
        System.out.println("开始时间:" + hai.getStartTime());
        System.out.println("结束时间:" + hai.getEndTime());
    }
}
}

到第4步完成,创建&查询&删除流程,启动流程,完成任务,任务查询,基本都有了。

仔细看一下工作流七大service简单介绍:

  1. repositoryService:流程仓库service,用于管理流程仓库,增删改查流程资源。
  2. runtimeService:运行时service,处理正在运行状态的流程实例,任务等。
  3. taskService:任务service,管理,查询任务,例如签收,办理,指派任务。
  4. historyService:历史service,可以查询所有历史数据,例如,流程实例,任务,活动,变量,附件等。
  5. managementService:引擎管理service,和具体业务无关,主要是查询引擎配置,数据库,作业等。
  6. identityService:身份service,可以管理和查询用户,组之间的关系。
  7. formService:表单service,处理正在运行状态的流程实例,任务等。

5.驳回操作

还没做完。。。

6.遇到的文档

英文版的用户手册:http://www.mossle.com/docs/activiti/5.21/index.html#api.services.deployment
中文版的用户手册(6.0):https://destinywang.github.io/blog/2018/11/26/Activiti%E5%B7%A5%E4%BD%9C%E6%B5%81%E5%BC%95%E6%93%8E/
一个Activity笔记:https://www.yuque.com/crow/java/mb02sd#H4iZ9


参考了很多:
http://791202.com/2020/03/29/spring/709/
https://www.cnblogs.com/chx9832/p/12667919.html
https://www.cnblogs.com/ahStudy/p/12672134.html
https://blog.csdn.net/qq_31784189/article/details/80873448

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342