activit和springboot都会不断的更新,网络上那么多教程,经常不说清楚版本的问题,浪费很多时间。
我参考官网的文档,选定了activiti7.1.0-M7,springboot2.1.13.RELEASE;
但是发现7.1.0-M7太新了,还没有相应的starter,就降低一下用7.1.0-M6
1.准备环境
创建一个新的项目或者Module,先修改pom文件
org.springframework.boot
spring-boot-starter-web
2.1.13.RELEASE
org.activiti
activiti-spring-boot-starter
7.1.0.M6
mysql
mysql-connector-java
5.1.45
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
然后,添加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从本地磁盘安装;
3.创建第一个流程文件
注意这个流程的名字叫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 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 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 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 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 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 list = taskService.createTaskQuery()
.processDefinitionKey("myProcess_leave")
.taskCandidateOrAssigned("teamleader")
.list();
if (list != null && list.size() > 0) {
for (Task task : list) {
Map variables = new HashMap();
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 map1 = (Map) taskService.getVariable(task.getId(), "参数");
for (Map.Entry m : map1.entrySet()) {
System.out.println("key:" + m.getKey() + " value:" + m.getValue());
}
Map map = task.getProcessVariables();
for (Map.Entry m : map.entrySet()) {
System.out.println("key:" + m.getKey() + " value:" + m.getValue());
}
for (Map.Entry m : task.getTaskLocalVariables().entrySet()) {
System.out.println("key:" + m.getKey() + " value:" + m.getValue());
}
}
}
}
/**
* 完成任务
*/
@Test
public void completeTask() {
securityUtil.logInAs("teamleader"); //指定组内任务人
Page 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 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简单介绍:
- repositoryService:流程仓库service,用于管理流程仓库,增删改查流程资源。
- runtimeService:运行时service,处理正在运行状态的流程实例,任务等。
- taskService:任务service,管理,查询任务,例如签收,办理,指派任务。
- historyService:历史service,可以查询所有历史数据,例如,流程实例,任务,活动,变量,附件等。
- managementService:引擎管理service,和具体业务无关,主要是查询引擎配置,数据库,作业等。
- identityService:身份service,可以管理和查询用户,组之间的关系。
- 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