文档章节

spring boot与activiti集成实战

fengyexjtu
 fengyexjtu
发布于 2016/11/23 23:47
字数 1590
阅读 10274
收藏 15

这是原作者的博客地址

http://wiselyman.iteye.com/blog/2285223 

代码格式混乱,我修正了一下.项目源码在:

http://git.oschina.net/fengyexjtu/spring-boot-activiti

流程设计

<?xml version='1.0' encoding='UTF-8'?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
             xmlns:activiti="http://activiti.org/bpmn"
             typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath"
             targetNamespace="http://www.activiti.org/test">
	<process id="joinProcess" name="Join process" isExecutable="true">
		<startEvent id="startevent1" name="Start">
			<extensionElements>
				<activiti:formProperty id="personId" name="person id" type="long"
				                       required="true"></activiti:formProperty>
				<activiti:formProperty id="compId" name="company Id" type="long"
				                       required="true"></activiti:formProperty>
			</extensionElements>
		</startEvent>
		<endEvent id="endevent1" name="End"></endEvent>
		<userTask id="ApprovalTask" name="Approval Task"
		          activiti:candidateUsers="${joinService.findUsers(execution)}" isForCompensation="true">
			<extensionElements>
				<activiti:formProperty id="joinApproved" name="Join Approved" type="enum">
					<activiti:value id="true" name="Approve"></activiti:value>
					<activiti:value id="false" name="Reject"></activiti:value>
				</activiti:formProperty>
			</extensionElements>
		</userTask>
		<sequenceFlow id="flow1" sourceRef="startevent1" targetRef="ApprovalTask"></sequenceFlow>
		<serviceTask id="AutoTask" name="Auto Task"
		             activiti:expression="${joinService.joinGroup(execution)}"></serviceTask>
		<sequenceFlow id="flow2" sourceRef="ApprovalTask" targetRef="AutoTask"></sequenceFlow>
		<sequenceFlow id="flow3" sourceRef="AutoTask" targetRef="endevent1"></sequenceFlow>
	</process>
</definitions>

 

 

 

流程解释:

流程最左边是开始,最右边结束,左二小人图标为用户任务(User Task)需要人参与操作,我们选择有权限的操作的人来源于Spring的bean方法activiti:candidateUsers=”${joinService.findUsers(execution)}”,左三齿轮图标为服务任务(Service Task),是自动执行的任务,自动调用Spring的bean方法。

 项目搭建

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.fengye.example</groupId>
	<artifactId>spring-boot-activiti</artifactId>
	<version>1.0-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>spring-boot-activiti</name>
	<description>Demo project for Spring Boot</description>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.0.RELEASE</version>
	</parent>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
		<activiti.version>5.21.0</activiti.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-rest</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>org.activiti</groupId>
			<artifactId>activiti-spring-boot-starter-basic</artifactId>
			<version>${activiti.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

 

application.properties配置

spring.jpa.hibernate.ddl-auto=update
spring.jpa.database=MYSQL
spring.datasource.url=jdbc:mysql://127.0.0.1:3307/spring-boot-activiti?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

 

 核心代码

实体类

Person.java

package com.fengye.example.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

/**
 * Created by jery on 2016/11/23.
 */
@Entity
public class Person {
	
	@Id
	@GeneratedValue
	private Long personId;
	
	private String personName;
	
	@ManyToOne(targetEntity = Comp.class)
	private Comp comp;
	
	public Person() {
		
	}
	
	public Person(String personName) {
		this.personName = personName;
	}
	
	public Long getPersonId() {
		return personId;
	}
	
	public void setPersonId(Long personId) {
		this.personId = personId;
	}
	
	public String getPersonName() {
		return personName;
	}
	
	public void setPersonName(String personName) {
		this.personName = personName;
	}
	
	public Comp getComp() {
		return comp;
	}
	
	public void setComp(Comp comp) {
		this.comp = comp;
	}
}

Comp.java

package com.fengye.example.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.util.List;

/**
 * Created by jery on 2016/11/23.
 */

@Entity
public class Comp {
	@Id
	@GeneratedValue
	private Long compId;
	private String compName;
	@OneToMany(mappedBy = "comp", targetEntity = Person.class)
	private List<Person> people;
	
	public Comp(String compName)
	{this.compName = compName;}
	
	public Comp() {
		
	}
	
	public Long getCompId() {
		return compId;
	}
	
	public void setCompId(Long compId) {
		this.compId = compId;
	}
	
	public String getCompName() {
		return compName;
	}
	
	public void setCompName(String compName) {
		this.compName = compName;
	}
	
	public List<Person> getPeople() {
		return people;
	}
	
	public void setPeople(List<Person> people) {
		this.people = people;
	}
}

 

DAO

package com.fengye.example.dao;

import com.fengye.example.model.Person;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Created by jery on 2016/11/23.
 */
public interface PersonRepository extends JpaRepository<Person, Long> {
	
	public Person findByPersonName(String personName);
	
}

 

package com.fengye.example.dao;

import com.fengye.example.model.Comp;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CompRepository extends JpaRepository<Comp, Long> {
	
}

 

Activiti服务

package com.fengye.example.service;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jery on 2016/11/23.
 */

@Service
@Transactional
public class ActivitiService {
	//注入为我们自动配置好的服务
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private TaskService taskService;
	
	//开始流程,传入申请者的id以及公司的id
	public void startProcess(Long personId, Long compId) {
		Map<String, Object> variables = new HashMap<String, Object>();
		variables.put("personId", personId);
		variables.put("compId", compId);
		runtimeService.startProcessInstanceByKey("joinProcess", variables);
	}
	
	//获得某个人的任务别表
	public List<Task> getTasks(String assignee) {
		return taskService.createTaskQuery().taskCandidateUser(assignee).list();
	}
	
	//完成任务
	public void completeTasks(Boolean joinApproved, String taskId) {
		Map<String, Object> taskVariables = new HashMap<String, Object>();
		taskVariables.put("joinApproved", joinApproved);
		taskService.complete(taskId, taskVariables);
	}
}

 

Service Task服务

package com.fengye.example.service;

import com.fengye.example.dao.CompRepository;
import com.fengye.example.dao.PersonRepository;
import com.fengye.example.model.Comp;
import com.fengye.example.model.Person;
import org.activiti.engine.delegate.DelegateExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * Created by jery on 2016/11/23.
 */
@Service
public class JoinService {
	@Autowired
	PersonRepository personRepository;
	@Autowired
	private CompRepository compRepository;
	
	//加入公司操作,可从DelegateExecution获取流程中的变量
	public void joinGroup(DelegateExecution execution) {
		Boolean bool = (Boolean) execution.getVariable("joinApproved");
		if (bool) {
			Long personId = (Long) execution.getVariable("personId");
			Long compId = (Long) execution.getVariable("compId");
			Comp comp = compRepository.findOne(compId);
			Person person = personRepository.findOne(personId);
			person.setComp(comp);
			personRepository.save(person);
			System.out.println("加入组织成功");
		} else {
			System.out.println("加入组织失败");
		}
	}
	
	//获取符合条件的审批人,演示这里写死,使用应用使用实际代码
	public List<String> findUsers(DelegateExecution execution) {
		return Arrays.asList("admin", "wtr");
	}
}

控制器

package com.fengye.example.controller;

/**
 * Created by jery on 2016/11/23.
 */

import com.fengye.example.service.ActivitiService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class MyRestController {
	@Autowired
	private ActivitiService myService;
	
	//开启流程实例
	@RequestMapping(value = "/process/{personId}/{compId}", method = RequestMethod.GET)
	public void startProcessInstance(@PathVariable Long personId, @PathVariable Long compId) {
		myService.startProcess(personId, compId);
	}
	
	//获取当前人的任务
	@RequestMapping(value = "/tasks", method = RequestMethod.GET)
	public List<TaskRepresentation> getTasks(@RequestParam String assignee) {
		List<Task> tasks = myService.getTasks(assignee);
		List<TaskRepresentation> dtos = new ArrayList<TaskRepresentation>();
		for (Task task : tasks) {
			dtos.add(new TaskRepresentation(task.getId(), task.getName()));
		}
		return dtos;
	}
	
	//完成任务
	@RequestMapping(value = "/complete/{joinApproved}/{taskId}", method = RequestMethod.GET)
	public String complete(@PathVariable Boolean joinApproved, @PathVariable String taskId) {
		myService.completeTasks(joinApproved, taskId);
		return "ok";
	}
	
	//Task的dto
	static class TaskRepresentation
	
	{
		private String id;
		private String name;
		
		public TaskRepresentation(String id, String name) {
			this.id = id;
			this.name = name;
		}
		
		public String getId() {
			return id;
		}
		
		public void setId(String id) {
			this.id = id;
		}
		
		public String getName() {
			return name;
		}
		
		public void setName(String name) {
			this.name = name;
		}
	}
}

入口类

import com.fengye.example.dao.CompRepository;
import com.fengye.example.dao.PersonRepository;
import com.fengye.example.model.Comp;
import com.fengye.example.model.Person;
import com.fengye.example.service.ActivitiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

/**
 * Created by jery on 2016/11/23.
 */

@SpringBootApplication
@ComponentScan("com.fengye.example")
@EnableJpaRepositories("com.fengye.example.dao")
@EntityScan("com.fengye.example.model")
public class ActivitiApplication {
   @Autowired
   private CompRepository compRepository;
   @Autowired
   private PersonRepository personRepository;
   
   
   public static void main(String[] args) {
      SpringApplication.run(ActivitiApplication.class, args);
   }
   
   //初始化模拟数据
   @Bean
   public CommandLineRunner init(final ActivitiService myService) {
      return new CommandLineRunner() {
         public void run(String... strings) throws Exception {
            if (personRepository.findAll().size() == 0) {
               personRepository.save(new Person("wtr"));
               personRepository.save(new Person("wyf"));
               personRepository.save(new Person("admin"));
            }
            if (compRepository.findAll().size() == 0) {
               Comp group = new Comp("great company");
               compRepository.save(group);
               Person admin = personRepository.findByPersonName("admin");
               Person wtr = personRepository.findByPersonName("wtr");
               admin.setComp(group); wtr.setComp(group);
               personRepository.save(admin); personRepository.save(wtr);
            }
         }
      };
   }
}

 

 演示

启动程序会自动初始化Activiti所用的数据库和我们的业务数据库,并自动发布我们的流程。

此时我们要加入的公司id为1,申请加入的人的id为2,使用PostMan访问http://localhost:8080/process/2/1 此时数据库发生如下变化

此时用户admin和wtr具备审批申请的权利,此时我们访问http://localhost:8080/tasks?assignee=admin 查看admin用户的任务,返回结果为:

  1. [
  2. {
  3. "id":"10",
  4. "name":"Approval Task"
  5. }
  6. ]

 

我们现在通过访问http://localhost:8080/complete/true/10 完成任务,true为同意(可以选择false),10为task的id,任务完成后会自动调用Service Task,此时wyf这条记录的comp_compId为更新为当前公司的id。

本文转载自:http://wiselyman.iteye.com/blog/2285223

共有 人打赏支持
fengyexjtu

fengyexjtu

粉丝 5
博文 49
码字总数 20075
作品 0
西安
程序员
加载中

评论(2)

l
long

引用来自“a43430096”的评论

你好 按照你分享的 我配置完了后 请求http://localhost:8080/activiti 弹出需要用户名密码 请问怎么处理啊
路人甲,推测你是不是用了比较高的spring boot版本。我遇到好像出现这种情况,要把spring security 验证功能关闭,才行。
a43430096
a43430096
你好 按照你分享的 我配置完了后 请求http://localhost:8080/activiti 弹出需要用户名密码 请问怎么处理啊
新书上架:《Spring Boot 开发实战》基于 Kotlin + Gradle + Spring Boot 2.0 的企业级服务端开发实战

新书上架:《Spring Boot 开发实战》 — 基于 Kotlin + Gradle + Spring Boot 2.0 的企业级服务端开发实战 京东下单链接 https://item.jd.com/31178320122.html 天猫下单链接 https://detail...

程序员诗人
08/22
0
0
新书上架:《Spring Boot 开发实战》(基于 Kotlin + Gradle + Spring Boot 2.0 的企业级服务端开发实战)

新书上架:《Spring Boot 开发实战》 — 基于 Kotlin + Gradle + Spring Boot 2.0 的企业级服务端开发实战 京东下单链接 https://item.jd.com/31178320122.html 天猫下单链接 https://detail...

程序员诗人
08/05
0
0
《 Kotlin + Spring Boot : K2EE 服务端开发实战 》

《 Kotlin + Spring Boot : K2EE 服务端开发实战 》 第一篇 Spring Boot 基础 第1章 Spring Boot 与 Kotlin 的极简理念 第2章 Spring Boot + Kotlin 快速开始 Hello World 第3章 Spring Boo...

程序员诗人
2017/11/02
0
0
kft-activiti-demo 1.13.0 发布,Activiti 快速入门 Demo

时隔一年再次更新,主要是针对Activiti 5.17+版本做了支持,自动初始化Demo数据等 Activiti Modeler从5.17开始结构和整合到项目的方式有些变化,另外官方Activiti Explorer整合的方式也有Spr...

咖啡兔
2015/11/25
1K
3
快速开发模块化脚手架 - lenos

lenos是一款快速开发模块化脚手架,采用spring boot2.0、spring、SpringMvc、mybatis、shiro、activiti工作流+swagger+ehcache+quartz+freemarker+layui技术进行开发,持久层集成tkmapper丰富...

一枚码农
03/06
0
3

没有更多内容

加载失败,请刷新页面

加载更多

百度贴吧发送gif图片的限制

百度贴吧中不可以发送超过500k的gif图片,同时尺寸不能超过700个像素。

gugudu
18分钟前
1
0
eclipse中查找所有汉字

今天遇到需要对中文翻译为英文的情况,需要查找一下项目中出现的所有汉字。我们可以使用快捷键Ctrl+H,在搜索一栏输入:[^\x00-\xff],记得勾选正则表达式。 备注: [\x00-\xff] 是 0 - 255的...

hengbao5
19分钟前
2
0
HBase常用操作命令

HBase – Hadoop Database,是一个高可靠性、高性能、面向列、可伸缩的分布式存储系统,利用HBase技术可在廉价PC Server上搭建起大规模结构化存储集群。 HBase是Google Bigtable的开源实现,...

飓风2000
24分钟前
1
0
天创恒达TC TC6C0更新固件包

天创恒达TC TC6C0 升级完 登录密码 admin、000000

yizhichao
25分钟前
1
0
阿里云总裁胡晓明:“这些新杭州故事,明天将会在更多城市发生”

摘要: 9月19日,2018杭州·云栖大会现场,杭州城市大脑2.0正式发布,管辖范围扩大28倍,覆盖面积增至420平方公里,相当于65个西湖大小。 ET城市大脑等数字化城市解决方案,掀开了“杭州故事...

阿里云官方博客
27分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部