Activiti7与SpringBoot 整合开发
介绍
流程定义如下:
流程如下:申请人提出请假申请后,上级领导看到进行审批,如果时间超过三天,需要校长复审,三天之内直接人事存档。
进入开发工作,具体步骤如下:
1.添加 SpringBoot 整合 Activti7 的坐标;
2.添加 SpringSecurity 安全框架的整合配置信息;
3.使用 Activti7 新支持的类来实现工作流开发:
a.ProcessRuntime 接口;
b.TaskRuntime 接口。
4.使用新的 API 实现工作流开发,主要包括:
a.流程定义查询;
b.启动流程实例;
c.任务的查询;
d.任务的完成。
SpringBoot 整合 Activiti7 的配置
SpringBoot 与 Activiti7 整合开发,我们在工程的 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.jsxy.test</groupId><artifactId>activiti.springboot</artifactId><version>1.0.0-SNAPSHOT</version><!--activiti7与SpringBoot整合的相关依赖--><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.0.RELEASE</version><relativePath/> <!-- lookup parent from repository --></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><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></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><!-- https://mvnrepository.com/artifact/org.activiti/activiti-spring-boot-starter --><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><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.27</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>
通过 pom.xml 文件中所导入的坐标,我们就可以实现 activiti7 与 Springboot 整合。
SpringBoot 的 application.yml 文件配置
Activiti7 生成的表放到 Mysql 数据库中,需要在 springboot 的配置文件 application.yml中添加相关的配置
spring:datasource:url: jdbc:mysql://localhost:3306/activiti_springboot_test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMTusername : rootpassword : rootrootdriver-class-name: com.mysql.jdbc.Driveractiviti:db-history-used: truehistory-level: audit
添加 SpringSecurity 安全框架整合配置
Activiti7 与 SpringBoot 整合后,默认情况下,集成了 SpringSecurity 安全框架,这样我们就要去准备 SpringSecurity 整合进来的相关用户权限配置信息。
可以查看一下整合 SpringBoot 的依赖包,发现同时也将 SpringSecurity 的依赖包也添加进项目中了,如下:
添加 SecurityUtil 类
添加 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 {@Autowiredprivate 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() {@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() {return user.getAuthorities();}@Overridepublic Object getCredentials() {return user.getPassword();}@Overridepublic Object getDetails() {return user;}@Overridepublic Object getPrincipal() {return user;}@Overridepublic boolean isAuthenticated() {return true;}@Overridepublic void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {}@Overridepublic String getName() {return user.getUsername();}}));org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(username);}
}
这个类可以从我们下载的 Activiti7 官方提供的 Example 中找到。
添加 DemoApplicationConfig 类
在 Activiti7 官方下载的 Example 中找到 DemoApplicationConfig 类,它的作用是为了实现SpringSecurity 框架的用户权限的配置,这样我们就可以在系统中使用用户权限信息。本次项目中基本是在文件中定义出来的用户信息,当然也可以是数据库中查询的用户权限信息。
/** Copyright 2018 Alfresco, Inc. and/or its affiliates.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/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@Autowiredpublic void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(myUserDetailsService());}@Beanpublic 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;}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}
使用 SpringBoot 整合 Junit 方式测试新特性
创建测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class ActivitiTest{@Autowiredprivate ProcessRuntime processRuntime;@Autowiredprivate TaskRuntime taskRuntime;@Autowiredprivate SecurityUtil securityUtil;
}
查看流程定义信息
/*** 查看流程定义*/@Testpublic void contextLoads() {securityUtil.logInAs("salaboy");Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 10));System.out.println("可用的流程定义数量:" + processDefinitionPage.getTotalItems());for (ProcessDefinition pd : processDefinitionPage.getContent()) {System.out.println("流程定义:" + pd);}}
通过 ProcessRuntime 的方法,我们可以查看已经部署的流程定义信息。通过加入 Pageable.of()方法可以实现分页查询效果。
启动流程实例
/*** 启动流程实例*/@Testpublic void testStartProcess() {securityUtil.logInAs("salaboy");ProcessInstance pi = processRuntime.start(ProcessPayloadBuilder.start().withProcessDefinitionKey("myProcess_1").build());System.out.println("流程实例ID:" + pi.getId());}
启动流程实例,我们可以使用 ProcessRuntime 的 start()方法就可以实现流程实例的启动。
查询并完成任务
/*** 查询任务,并完成自己的任务*/@Testpublic void testTask() {securityUtil.logInAs("erdemedeiros");Page<Task> taskPage=taskRuntime.tasks(Pageable.of(0,10));if (taskPage.getTotalItems()>0){for (Task task:taskPage.getContent()){taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());System.out.println("任务:"+task);taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId()).build());}}Page<Task> taskPage2=taskRuntime.tasks(Pageable.of(0,10));if (taskPage2.getTotalItems()>0){System.out.println("任务:"+taskPage2.getContent());}}
使用 TaskRuntime 接口的 tasks()方法实现任务的查询。
使用 TaskRuntime 接口的 claim()方法实现任务拾取。
使用 TaskRuntime 接口的 complete()方法实现任务的完成。
附启动类代码:
import org.activiti.api.process.runtime.connector.Connector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class Actviti7DemoApplication {private Logger logger = LoggerFactory.getLogger(Actviti7DemoApplication.class);public static void main(String[] args) {SpringApplication.run(Actviti7DemoApplication.class, args);}@Beanpublic Connector testConnector() {return integrationContext -> {logger.info("我被调用啦~~");return integrationContext;};}
}