最近自己独立弄一个activiti项目,写一下整合过程:
环境:jdk1.7 tomcat7.0 maven3.5 eclipse mysql5.5
--我的工程结构,怎么创建一个maven项目就不在这里写了:
--首先见表
CREATE TABLE `t_user` (
`USER_ID` int(11) NOT NULL auto_increment,
`USER_NAME` char(30) NOT NULL,
`USER_PASSWORD` char(10) NOT NULL,
`USER_EMAIL` char(30) NOT NULL,
PRIMARY KEY (`USER_ID`),
KEY `IDX_NAME` (`USER_NAME`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
--随便插入几条数据
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (1, 'aa', '1234567', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (2, 'cc', '1234567', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (3, 'dd', '1234567', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (4, 'ee', '1234567', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (5, 'artaahur', '1234567', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (6, 'vvvv', '1234567', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (7, 'ffff', '1234567', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (8, 'aaaa', '1234567', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (9, 'aaaaa', '1234567', '[email protected]');
INSERT INTO t_user (USER_ID, USER_NAME, USER_PASSWORD, USER_EMAIL) VALUES (10, 'vvvvvv', '1234567', '[email protected]');
---上面数据库的操作到这里就够了。
-----pom文件----
-----整合springMvc之前,先整合activiti和spring+mybatis
------mybatis-cfg.xml
"http://mybatis.org/dtd/mybatis-3-config.dtd">
-------spring-mvc.xml包涵spring配置和activiti配置
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
-----log4j.properties配置
log4j.rootLogger=DEBUG,Console,Stdout
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.appender.Stdout = org.apache.log4j.DailyRollingFileAppender
log4j.appender.Stdout.File = D://logs/bpmnTest.log
log4j.appender.Stdout.Append = true
log4j.appender.Stdout.Threshold = DEBUG
log4j.appender.Stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.Stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
----下面创建实体类
package com.travesky.bluesky.activiti.domain;
/**
*
* @author Ancan
*
*/
public class User {
private Integer userId;
private String userName;
private String userPassword;
private String userEmail;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName
+ ", userPassword=" + userPassword + ", userEmail=" + userEmail
+ "]";
}
}
--创建mybatis的mapper映射文件
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
---创建mapper映射的实体类
package com.travesky.bluesky.activiti.dao;
import com.travesky.bluesky.activiti.domain.User;
/**
*
* @author Ancan
*
*/
public interface UserDao {
public User selectUserById(Integer userId);
}
----创建service
--userService
package com.travesky.bluesky.activiti.service;
import com.travesky.bluesky.activiti.domain.User;
public interface UserService {
User selectUserById(Integer userId);
}
----UserServiceImpl
package com.travesky.bluesky.activiti.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.travesky.bluesky.activiti.dao.UserDao;
import com.travesky.bluesky.activiti.domain.User;
import com.travesky.bluesky.activiti.service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
public User selectUserById(Integer userId) {
return userDao.selectUserById(userId);
}
}
-----上面已经整合完成,下面进行测试
--测试目录结构
------BaseTestCase
package com.simple.activiti.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
/**
* 加载activiti的23张表的运行例子
* @author AnCan
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-activiti.xml"})
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false)
@Transactional
public class BaseTestCase extends AbstractTransactionalJUnit4SpringContextTests{
@Test
/**
* 运行此方法,加载activiti的数据库表信息
*/
public void test(){
System.out.println ("test");
}
}
------UserserviceTest
package com.simple.activiti.test.user;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.simple.activiti.test.BaseTestCase;
import com.travesky.bluesky.activiti.domain.User;
import com.travesky.bluesky.activiti.service.UserService;
public class UserserviceTest extends BaseTestCase {
@Autowired
private UserService userService;
Logger logger = Logger.getLogger(UserserviceTest.class);
@Test
public void selectUserByIdTest(){
User user = userService.selectUserById(10);
logger.debug("查找结果" + user);
}
}
------BpmDefinitionTest---- 主要测试动态流程图和流程文件的生成其中遇到问题请参照的相关记录
package com.simple.activiti.test.bpm;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.activiti.bpmn.BpmnAutoLayout;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.EndEvent;
import org.activiti.bpmn.model.ExclusiveGateway;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.ImplementationType;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.bpmn.model.ServiceTask;
import org.activiti.bpmn.model.StartEvent;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
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.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import com.simple.activiti.test.BaseTestCase;
public class BpmDefinitionTest extends BaseTestCase{
@Resource
private RepositoryService repositoryService;
@Resource
private RuntimeService runtimeService;
@Resource
TaskService taskService;
@Test
public void testDeploy() throws IOException{
InputStream is=readXmlFile();
Assert.assertNotNull(is);
//发布流程
Deployment deployment=repositoryService.createDeployment().addInputStream("bpmn20.xml", is).name("holidayRequest").deploy();
Assert.assertNotNull(deployment);
System.out.println("deployId:" + deployment.getId());
//查询流程定义
ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
Long businessKey=new Double(1000000*Math.random()).longValue();
//启动流程
runtimeService.startProcessInstanceById(processDefinition.getId(),businessKey.toString());
//查询任务实例
List
Assert.assertNotNull(taskList==null);
Assert.assertTrue(taskList.size()>0);
for(Task task:taskList){
System.out.println("task name is " + task.getName() + " ,task key is " + task.getTaskDefinitionKey());
}
}
public InputStream readXmlFile() throws IOException{
String filePath="holidayRequest.bpmn";
return Class.class.getClass().getResource("/"+filePath).openStream();
}
@Test
public void testDynamicDeploy() throws Exception {
//创建bpmn模型
BpmnModel model = new BpmnModel();
org.activiti.bpmn.model.Process process = new org.activiti.bpmn.model.Process();
model.addProcess(process);
process.setId("my-process");
//创建bpmn元素
process.addFlowElement(createStartEvent());
process.addFlowElement(createUserTask("task1", "First task", "fred"));
process.addFlowElement(createUserTask("task2", "Second task", "john"));
process.addFlowElement(createEndEvent());
process.addFlowElement(createSequenceFlow("start", "task1"));
process.addFlowElement(createSequenceFlow("task1", "task2"));
process.addFlowElement(createSequenceFlow("task2", "end"));
// 2.生成BPMN自动布局
new BpmnAutoLayout(model).execute();
// 3. 部署这个BPMN模型
Deployment deployment = repositoryService.createDeployment()
.addBpmnModel("dynamic-model.bpmn", model).name("Dynamic process deployment")
.deploy();
// 4. 启动流程实例
ProcessInstance processInstance = runtimeService
.startProcessInstanceByKey("my-process");
// 5 发起任务
List
.processInstanceId(processInstance.getId()).list();
Assert.assertEquals(1, tasks.size());
Assert.assertEquals("First task", tasks.get(0).getName());
Assert.assertEquals("fred", tasks.get(0).getAssignee());
// 6. 保存bpmn流程图
InputStream processDiagram = repositoryService
.getProcessDiagram(processInstance.getProcessDefinitionId());
FileUtils.copyInputStreamToFile(processDiagram, new File("target/diagram.png"));
// 7. 保存为bpmn.xml的xml类型文件
InputStream processBpmn = repositoryService
.getResourceAsStream(deployment.getId(), "dynamic-model.bpmn");
FileUtils.copyInputStreamToFile(processBpmn,
new File("target/process.bpmn20.xml"));
}
@Test
public void testDynamicDeploy2() throws Exception {
System.out.println(".........start...");
// 1. Build up the model from scratch
BpmnModel model = new BpmnModel();
org.activiti.bpmn.model.Process process=new org.activiti.bpmn.model.Process();
model.addProcess(process);
final String PROCESSID ="process8888888888";
final String PROCESSNAME ="测试0100000";
process.setId(PROCESSID);
process.setName(PROCESSNAME);
process.addFlowElement(createStartEvent());
process.addFlowElement(createUserTask("task1", "节点01", "candidateGroup1"));
process.addFlowElement(createExclusiveGateway("createExclusiveGateway1"));
process.addFlowElement(createUserTask("task2", "节点02", "candidateGroup2"));
process.addFlowElement(createExclusiveGateway("createExclusiveGateway2"));
process.addFlowElement(createUserTask("task3", "节点03", "candidateGroup3"));
process.addFlowElement(createExclusiveGateway("createExclusiveGateway3"));
process.addFlowElement(createUserTask("task4", "节点04", "candidateGroup4"));
process.addFlowElement(createEndEvent());
process.addFlowElement(createSequenceFlow("startEvent", "task1", "", ""));
process.addFlowElement(createSequenceFlow("task1", "task2", "", ""));
//
process.addFlowElement(createSequenceFlow("task2", "createExclusiveGateway1"));
process.addFlowElement(createSequenceFlow("createExclusiveGateway1", "task1", "不通过", "${pass=='2'}"));
process.addFlowElement(createSequenceFlow("createExclusiveGateway1", "task3", "通过", "${pass=='1'}"));
process.addFlowElement(createSequenceFlow("task3", "createExclusiveGateway2"));
process.addFlowElement(createSequenceFlow("createExclusiveGateway2", "task2", "不通过", "${pass=='2'}"));
process.addFlowElement(createSequenceFlow("createExclusiveGateway2", "task4", "通过", "${pass=='1'}"));
process.addFlowElement(createSequenceFlow("task4", "createExclusiveGateway3"));
process.addFlowElement(createSequenceFlow("createExclusiveGateway3", "task3", "不通过", "${pass=='2'}"));
process.addFlowElement(createSequenceFlow("createExclusiveGateway3", "end", "通过", "${pass=='1'}"));
try {
// 2. Generate graphical information
new BpmnAutoLayout(model).execute();
} catch (Exception e) {
e.printStackTrace();
}
// 3. Deploy the process to the engine
Deployment deployment = repositoryService.createDeployment().addBpmnModel(PROCESSID+".bpmn", model).name(PROCESSID+"_deployment").deploy();
// 4. Start a process instance
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(PROCESSID);
// 5. Check if task is available
List
Assert.assertEquals(1, tasks.size());
// 6. Save process diagram to a file
InputStream processDiagram = repositoryService.getProcessDiagram(processInstance.getProcessDefinitionId());
FileUtils.copyInputStreamToFile(processDiagram, new File("target/"+PROCESSID+".png"));
// 7. Save resulting BPMN xml to a file
InputStream processBpmn = repositoryService.getResourceAsStream(deployment.getId(), PROCESSID+".bpmn");
FileUtils.copyInputStreamToFile(processBpmn,new File("target/"+PROCESSID+".bpmn.xml"));
System.out.println(".........end...");
}
//创建task
protected UserTask createUserTask(String id, String name, String assignee) {
UserTask userTask = new UserTask();
userTask.setName(name);
userTask.setId(id);
userTask.setAssignee(assignee);
List
candidateUsers.add("xiaoli");
candidateUsers.add("xiaoli1");
candidateUsers.add("xiaoli2");
candidateUsers.add("xiaoli3");
userTask.setCandidateUsers(candidateUsers);
return userTask;
}
//创建箭头
protected SequenceFlow createSequenceFlow(String from, String to) {
SequenceFlow flow = new SequenceFlow();
flow.setSourceRef(from);
flow.setTargetRef(to);
return flow;
}
protected StartEvent createStartEvent() {
StartEvent startEvent = new StartEvent();
startEvent.setId("start");
return startEvent;
}
/**
* 排他网关
*/
protected static ExclusiveGateway createExclusiveGateway(String id) {
ExclusiveGateway exclusiveGateway = new ExclusiveGateway();
exclusiveGateway.setId(id);
return exclusiveGateway;
}
protected EndEvent createEndEvent() {
EndEvent endEvent = new EndEvent();
endEvent.setId("end");
return endEvent;
}
/*连线*/
protected static SequenceFlow createSequenceFlow(String from, String to,String name,String conditionExpression) {
SequenceFlow flow = new SequenceFlow();
flow.setSourceRef(from);
flow.setTargetRef(to);
flow.setName(name);
if(null!=conditionExpression&&!"".equals(conditionExpression)){
flow.setConditionExpression(conditionExpression);
}
return flow;
}
protected FlowElement createServiceTask(String name){
ServiceTask stask = new ServiceTask();
stask.setId("sid");
stask.setName(name);
stask.setImplementation("activitiTest.PrintVariables");
String implementationType = ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION;
stask.setImplementationType(implementationType );
return stask;
}
}
-------右键运行测试方法,完成测试。没有配置activiti的数据库,在运行完后会自动创建表。
----- 在src/main/resource中添加springmvc文件夹,然后添加文件spring-mvc.xml,内容如下:
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
-----配置web,xml
----web.xml
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
------
- <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
- <html>
- <body>
- <h2>Hello World!h2>
- ${user.userId}<br>
- ${user.userName}<br>
- ${user.userPassword}<br>
- ${user.userEmail}<br>
- body>
- html>
-----最后就是controller的书写了
package com.travesky.bluesky.activiti.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestMapping;
import com.travesky.bluesky.activiti.domain.User;
import com.travesky.bluesky.activiti.service.UserService;
/**
*
* @author Ancan
*
*/
@Controller
public class UserController {
@Resource
private UserService userService;
@RequestMapping("/")
public ModelAndView getIndex(){
ModelAndView mav = new ModelAndView("index");
User user = userService.selectUserById(1);
mav.addObject("user", user);
return mav;
}
}
-----到这里,已经全部整合完毕,但是,由于是maven项目,在转换成web项目后,我们要添加jar的依赖到项目
--右键项目,properties---》deployment Assembly-->点击add,添加jar包如下图
-----添加完依赖后,就可以通过tomcat运行项目了