开发OA人力资源管理系统时在人员调动时、请假审批等需要使用到工作流,以此作为学习契机。
工作流学习日志(Activiti7基础-概念、基本api使用)
工作流学习日志 -(Activiti7进阶)
工作流学习日志-(Activiti7与spring、SpringBoot整合)
与spring整合时的pom.xml文件依赖。
<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.0modelVersion>
<groupId>com.xxxgroupId>
<artifactId>actspringdemoartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<slf4j.version>1.6.6slf4j.version>
<log4j.version>1.2.12log4j.version>
properties>
<dependencies>
<dependency>
<groupId>org.activitigroupId>
<artifactId>activiti-engineartifactId>
<version>7.0.0.Beta1version>
dependency>
<dependency>
<groupId>org.activitigroupId>
<artifactId>activiti-springartifactId>
<version>7.0.0.Beta1version>
dependency>
<dependency>
<groupId>org.activitigroupId>
<artifactId>activiti-bpmn-modelartifactId>
<version>7.0.0.Beta1version>
dependency>
<dependency>
<groupId>org.activitigroupId>
<artifactId>activiti-bpmn-converterartifactId>
<version>7.0.0.Beta1version>
dependency>
<dependency>
<groupId>org.activitigroupId>
<artifactId>activiti-json-converterartifactId>
<version>7.0.0.Beta1version>
dependency>
<dependency>
<groupId>org.activitigroupId>
<artifactId>activiti-bpmn-layoutartifactId>
<version>7.0.0.Beta1version>
dependency>
<dependency>
<groupId>org.activiti.cloudgroupId>
<artifactId>activiti-cloud-services-apiartifactId>
<version>7.0.0.Beta1version>
dependency>
<dependency>
<groupId>aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.5.4version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.40version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>5.0.7.RELEASEversion>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-nopartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.5version>
dependency>
<dependency>
<groupId>commons-dbcpgroupId>
<artifactId>commons-dbcpartifactId>
<version>1.4version>
dependency>
dependencies>
<repositories>
<repository>
<id>alfrescoid>
<name>Activiti Releasesname>
<url>https://artifacts.alfresco.com/nexus/content/repositories/activiti-releases/url>
<releases>
<enabled>trueenabled>
releases>
repository>
repositories>
project>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/actspring"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="maxActive" value="3"/>
<property name="maxIdle" value="1"/>
bean>
<bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration">
<property name="dataSource" ref="dataSource"/>
<property name="transactionManager" ref="transactionManager"/>
<property name="databaseSchemaUpdate" value="drop-create"/>
bean>
<bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean">
<property name="processEngineConfiguration" ref="processEngineConfiguration"/>
bean>
<bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService"/>
<bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService"/>
<bean id="taskService" factory-bean="processEngine" factory-method="getTaskService"/>
<bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
tx:attributes>
tx:advice>
beans>
配置文件中的数据库策略databaseSchemaUpdate有以下几个值
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:activiti-spring.xml")
public class TestActSpring {
@Autowired
private RepositoryService repositoryService;
@Test
public void test01(){
System.out.println("部署对象="+repositoryService);
}
}
执行流程:
与SpringBoot进行整合的主要依赖是activiti-spring-boot-starter。
<modelVersion>4.0.0modelVersion>
<groupId>com.xxxgroupId>
<artifactId>actspringbootdemoartifactId>
<version>1.0-SNAPSHOTversion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.4.1version>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
dependency>
<dependency>
<groupId>org.activitigroupId>
<artifactId>activiti-spring-boot-starterartifactId>
<version>7.0.0.Beta2version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.40version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<version>2.4.1version>
plugin>
plugins>
build>
需要在application.yml配置文件中配置数据库的数据源、activiti相关配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/actspringboot?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
username: root
password: root
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
#检测历史表是否存在 activiti7默认没有开启数据库历史记录 启动数据库历史记录
db-history-used: true
#记录历史等级 可配置的历史级别有none, activity, audit, full
#none:不保存任何的历史数据,因此,在流程执行过程中,这是最高效的。
#activity:级别高于none,保存流程实例与流程行为,其他数据不保存。
#audit:除activity级别会保存的数据外,还会保存全部的流程任务及其属性。audit为history的默认值。
#full:保存历史数据的最高级别,除了会保存audit级别的数据外,还会保存其他全部流程相关的细节数据,包括一些 流程参数等。
history-level: full
#校验流程文件,默认校验resources下的processes文件夹里的流程文件
#check-process-definitions: false
/**
* 设置用户和角色
*/
@Configuration
public class DemoApplicationConfiguration {
private Logger log = LoggerFactory.getLogger(DemoApplicationConfiguration.class);
@Bean
public UserDetailsService myUserDetailsService(){
//创建将用户的详情信息存在内存中的对象。
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
//设置用户的信息、用户角色
String[][] usersGroupAndRoles = {
{"jack","password","ROLE_ACTIVITI_USER","GROUP_activitiTeam"},
{"rose","password","ROLE_ACTIVITI_USER","GROUP_activitiTeam"},
{"tom","password","ROLE_ACTIVITI_USER","GROUP_activitiTeam"},
{"jerry","password","ROLE_ACTIVITI_USER","GROUP_activitiTeam"},
{"other","password","ROLE_ACTIVITI_USER","GROUP_otherTeam"},
{"system","password","ROLE_ACTIVITI_USER"},
{"admin","password","ROLE_ACTIVITI_ADMIN"},
};
for (String[] users : usersGroupAndRoles) {
//用户的角色和组
List<String> authoritiesStrings = Arrays.asList(Arrays.copyOfRange(users, 2, users.length));
log.info("> Registering new user: {} with the following Authorities:[{}]",users[0],authoritiesStrings);
//将用户信息存储在内存中,参数一:用户名,参数二:用户密码,参数三:用户的角色和组。
inMemoryUserDetailsManager.createUser(new User(users[0],
passwordEncoder().encode(users[1]),
authoritiesStrings.stream().map(str -> new SimpleGrantedAuthority(str)).collect(Collectors.toList())));
}
return inMemoryUserDetailsManager;
}
/**
* 用户密码加密
* @return
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
当Activiti7与SpringBoot整合之后,默认集成了SpringSecurity权限框架。所以我们需要对该框架进行整合。
@Component
public class SecurityUtil {
private Logger logger = LoggerFactory.getLogger(SecurityUtil.class);
@Autowired
@Qualifier("myUserDetailsService")
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");
}
logger.info("> Logged in as: " + username);
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);
}
}
Activiti7可以自动部署流程,默认位置在resource目录下的processes目录中。没有该目录需要自己进行创建,用户存放bpmn文件。
在使用权限安全框架之后,任务的负责人需要设置在用户组Candidate Groups当中。Candidate Groups中的内容要与上面的ApplicationConfiguration类中出现的用户组名称保持一致。例如填写上面的activitiTeam、otherTeam。那么当不确定谁来负责当前任务的时候,只要登录的用户是当前用户组的,那么就可以拾取这个任务。
@SpringBootTest
public class Activiti7DemoApplicationTest {
private Logger log = LoggerFactory.getLogger(Activiti7DemoApplicationTest.class);
@Autowired
private TaskRuntime taskRuntime;
@Autowired
private ProcessRuntime processRuntime;
@Autowired
private SecurityUtil securityUtil;
/**
* 查看流程定义内容
* Activiti7可以自动部署流程
*/
@Test
public void findProcess(){
//设置登录用户。必须有一个登陆者,否则启动报错(虽然没有这句可以创建数据库表)
securityUtil.logInAs("jack");
//流程定义的分页对象
Page<ProcessDefinition> definitionPage = processRuntime.processDefinitions(Pageable.of(0, 10));
log.info("可用的流程定义总数:{}",definitionPage.getTotalItems());
for (ProcessDefinition processDefinition : definitionPage.getContent()) {
System.out.println("===================================");
log.info("流程定义内容:{}",processDefinition);
System.out.println("===================================");
}
}
/**
* 启动流程
*/
@Test
public void startProcess(){
//设置登陆用户
securityUtil.logInAs("system");
//ProcessPayloadBuilder是activiti7中提供的api以后启动以及完成任务都需要使用该方法进行操作
ProcessInstance processInstance = processRuntime
.start(ProcessPayloadBuilder.start().withProcessDefinitionKey("mydemo").build());
log.info("流程实例的内容:{}",processInstance);
}
/**
* 执行并完成任务
*/
@Test
public void doTask(){
//设置登陆用户(登陆的用户必须拥有权限,否则方法可以执行成功,但是数据库没有存储数据)
securityUtil.logInAs("rose");
//查询用户
Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, 10));
for (Task task : tasks.getContent()) {
//拾取任务
taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
log.info("任务内容:{}",task);
taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId()).build());
}
}
}
目前为止只是了解activiti的基本使用方法,还需要在工作中根据业务实现实际工作中工作流的使用。