SpringBoot 整合 Activti7 的具体步骤大概包括以下4步:
1.添加 SpringBoot 整合 Activti7 的相关jar包
2.添加 SpringSecurity 安全框架的整合配置信息
3.使用 Activti7 新支持的类来实现工作流开发
ProcessRuntime 接口
TaskRuntime 接口
4.使用新的 API 实现工作流开发,主要包括
流程定义查询
启动流程实例
任务的查询
任务的完成
接下来进行代码的编写
一、创建maven项目,添加 SpringBoot 整合 Activti7 的相关jar包,编写pom.xml文件
<?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
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.my.withub</groupId>
<artifactId>ActivitiSpringBoot</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--连接mysql数据库-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--activiti与springboot整合包-->
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-spring-boot-starter</artifactId>
<version>7.0.0.Beta2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
二、添加数据库连接相关配置信息,编写application.yml配置文件以及log4j.properties日志信息文件
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/activiti?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
username : root
password : 123456
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
三、添加 SecurityUtil 类。
为了能够快速实现 SpringSecurity 安全框架的配置,所添加的一个组件。
import org.springframework.beans.factory.annotation.Autowired;
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 java.util.Collection;
@Component
public class SecurityUtil {
@Autowired
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);
}
}
四、添加 DemoApplicationConfig 类
在 Activiti7 官方下载的 Example 中可以找到 DemoApplicationConfig 类,它的作用是为了实现SpringSecurity 框架的用户权限的配置,这样我们就可以在系统中使用用户权限信息。本次项目中基本是在文件中定义出来的用户信息,当然也可以是数据库中查询的用户权限信息。
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 = {
{"salaboy", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
{"ryandawsonuk", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
{"erdemedeiros", "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();
}
}
四、添加bpmn文件,为了能自动部署,我们需要将bpmn文件保存在resources/processes文件夹下
绘制流程图,如下图所示:
如下图所示,我们需要指定任务执行人
Assignee:直接设置任务执行人
Candidate-user:设置候选用户,格式:zhangsan,lisi,wangwu, 使用这种格式依然要指定具体的用户信息
Candiate-Groups:特点不需要知道具体的用户信息,使用这种格式只需要知道组名就可以
为了方便我们这次使用Candiate-Groups这种方式,从DemoApplicationConfig 类我们可以看到目前有两个组
这次使用activitiTeam这个组的人员来完成任务,如图所示,将每个节点的Candiate-Groups设置为activitiTeam
五、编写测试类,实现 SpringBoot 与 Junit 整合测试 Activiti7 所需的各种 API
/**
* SpringBoot与Junit整合,测试流程定义的相关操作
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ActivitiTest {
@Autowired
private ProcessRuntime processRuntime; // 实现流程定义相关操作
@Autowired
private TaskRuntime taskRuntime; //任务相关操作的类
@Autowired
private SecurityUtil securityUtil; // springSecurity相关的工具类
}
六、测试类中编写代码,查看流程定义
// 查看流程定义信息 流程部署在activiti7与springboot整合后,会自动部署,前提是必须将bpmn文件放到resource/processes目录下
@Test
public void queryProcessDefined(){
// springsecurity的相关认证
securityUtil.logInAs("salaboy");
// 分页查询出流程定义信息
Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 10));
System.out.println("可用的流程定义个数:"+processDefinitionPage.getTotalItems());
// 得到当前部署的每一个流程定义的信息processDefinitionPage.getContent()
for (Object pd : processDefinitionPage.getContent()) {
System.out.println("流程定义:"+pd);
}
}
通过 ProcessRuntime 的方法,可以查看已经部署的流程定义信息。通过加入 Pageable.of()方法可以实现分页查询效果。
同时,数据库会生成相关表,如下图所示:
七、通过 ProcessRuntime 的 start()方法启动流程实例
// 启动流程实例
@Test
public void startProcessInstance(){
// springsecurity的相关认证
securityUtil.logInAs("salaboy");
ProcessInstance processInstance = processRuntime.start(ProcessPayloadBuilder.start()
.withProcessDefinitionKey("holiday").build());
System.out.println("流程实例ID:"+processInstance.getId());
}
运行程序,可以看到流程实例ID,如下图所示:
查看数据库表,如下图所示:
接下来,通过TaskRuntime 接口的 tasks()方法实现任务的查询,TaskRuntime 接口的 claim()方法实现任务拾取, TaskRuntime 接口的 complete()方法实现任务的完成
//查询任务并完成
@Test
public void queryTask(){
// springsecurity的相关认证,相当于指定登录用户
securityUtil.logInAs("ryandawsonuk");
// 分页查询任务列表
Page<Task> taskPage = taskRuntime.tasks(Pageable.of(0, 10));
// 判断是否有任务
if(taskPage.getTotalItems()>0){
for (Task task : taskPage.getContent()) {
System.out.println("任务:"+task);
//拾取任务
taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
// 完成任务
taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId()).build());
}
}
// 任务完成后再次查询
taskPage = taskRuntime.tasks(Pageable.of(0, 10));
// 判断是否有任务
if(taskPage.getTotalItems()>0){
for (Task task : taskPage.getContent()) {
System.out.println("任务完成后的下一任务:"+task);
}
}
}
运行程序,我们可以看到任务的相关信息,如下图所示:
以此类推,我们可以完成一个完整的任务,这样我们就完成了Activiti7与SpringBoot整合开发,同时,我们也可以将SpringMVC也整合进来
首先,添加Controller类
/**
* 控制器
* 完成任务
*/
@RestController
public class ActivitiController {
private Logger logger = LoggerFactory.getLogger(ActivitiController.class);
@Autowired
private ProcessRuntime processRuntime; // 实现流程定义相关操作
@Autowired
private TaskRuntime taskRuntime; //任务相关操作的类
@Autowired
private SecurityUtil securityUtil; // springSecurity相关的工具类
}
然后,实现任务查询拾取及完成操作
// 查询任务并完成
@RequestMapping("/hello")
public void testHello(){
// springsecurity的相关认证,相当于指定登录用户
// securityUtil.logInAs("ryandawsonuk");
// 分页查询任务列表
Page<Task> taskPage = taskRuntime.tasks(Pageable.of(0, 10));
// 判断是否有任务
if(taskPage.getTotalItems()>0){
for (Task task : taskPage.getContent()) {
System.out.println("任务:"+task);
//拾取任务
taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
// 完成任务
taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId()).build());
}
}
// 任务完成后再次查询
taskPage = taskRuntime.tasks(Pageable.of(0, 10));
// 判断是否有任务
if(taskPage.getTotalItems()>0){
for (Task task : taskPage.getContent()) {
System.out.println("任务完成后的下一任务:"+task);
}
}
}
接下来,编写SpringBoot启动类
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class Application {
private Logger logger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}