1. 程式人生 > >springMvc+mybatis+spring 整合 包涵整合activiti 基於maven

springMvc+mybatis+spring 整合 包涵整合activiti 基於maven

最近自己獨立弄一個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檔案----

<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.simple.activiti.demo</groupId>
	<artifactId>activiti</artifactId>
	<version>1.0.0-SNAPSHOT</version>
	<dependencies>
		<!-- activiti begin -->
		<dependency>
			<groupId>org.activiti</groupId>
			<artifactId>activiti-engine</artifactId>
			<version>5.15.1</version>
		</dependency>
		<dependency>
			<groupId>org.activiti</groupId>
			<artifactId>activiti-spring</artifactId>
			<version>5.15.1</version>
		</dependency>
		<dependency>
			<groupId>org.activiti</groupId>
			<artifactId>activiti-bpmn-model</artifactId>
			<version>5.15.1</version>
		</dependency>
		<dependency>
			<groupId>org.activiti</groupId>
			<artifactId>activiti-bpmn-layout</artifactId>
			<version>5.15.1</version>
		</dependency>
		<dependency>
			<groupId>org.activiti</groupId>
			<artifactId>activiti-bpmn-converter</artifactId>
			<version>5.15.1</version>
		</dependency>
		<dependency>
			<groupId>org.activiti</groupId>
			<artifactId>activiti-process-validation</artifactId>
			<version>5.15.1</version>
		</dependency>
		<!-- activiti end -->
		<!-- mysql驅動包 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.29</version>
		</dependency>
		<!-- spring begin -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<!--spring單元測試依賴 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<!-- spring end -->
		<!-- springmvc begin -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.2.2.RELEASE</version>
		</dependency>
		<!-- springmvc end -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.5</version>
		</dependency>
		<!-- mybatis/spring包 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.2.0</version>
		</dependency>
		<!-- junit相關 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
		</dependency>
		<!-- log manger begin -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.6</version>
		</dependency>

		<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>2.1</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>1.7.6</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.6</version>
		</dependency>
		<!-- log manger end -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>javax.annotation-api</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<!-- spring MVC 在轉換為web專案後新增的begin -->
		<!-- javaee-api包 注意和專案使用的JDK版本對應 -->
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>7.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- javaee-web-api包 注意和專案使用的JDK版本對應 -->
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-web-api</artifactId>
			<version>7.0</version>
			<scope>provided</scope>
		</dependency>
		<!-- spring MVC end -->
	</dependencies>
</project>

-----整合springMvc之前,先整合activiti和spring+mybatis

------mybatis-cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>

-------spring-activiti.xml包涵spring配置和activiti配置

<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:tx="http://www.springframework.org/schema/tx" 
	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">
	<!-- spring 整合mybaitis begin -->
	<!-- 引入jdbc配置檔案 -->
	<!-- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> -->
	<!-- <property name="locations"> -->
	<!-- <list> -->
	<!-- <value>classpath:properties/*.properties</value> -->
	<!-- 要是有多個配置檔案,只需在這裡繼續新增即可 -->
	<!-- </list> -->
	<!-- </property> -->
	<!-- </bean> -->

	<!-- 
	ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration();
	//連線資料庫的配置
	processEngineConfiguration.setJdbcDriver("com.mysql.jdbc.Driver");
	processEngineConfiguration.setJdbcUrl("jdbc:mysql://localhost:3306/itcast0711activiti?useUnicode=true&characterEncoding=utf8");
	processEngineConfiguration.setJdbcUsername("root");
	processEngineConfiguration.setJdbcPassword("root");

	/**
	public static final String DB_SCHEMA_UPDATE_FALSE = "false";不能自動建立表,需要表存在
	public static final String DB_SCHEMA_UPDATE_CREATE_DROP = "create-drop";先刪除表再建立表
	public static final String DB_SCHEMA_UPDATE_TRUE = "true";如果表不存在,自動建立表
	*/
	processEngineConfiguration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
	-->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
		<!-- 連線資料的配置 -->
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/activiti?useUnicode=true&amp;characterEncoding=utf8"></property>
		<property name="username" value="root"></property>
		<property name="password" value="root"></property>
		<!-- 使用properties來配置 -->
		<!-- <property name="driverClassName"> -->
		<!-- <value>${jdbc_driverClassName}</value> -->
		<!-- </property> -->
		<!-- <property name="url"> -->
		<!-- <value>${jdbc_url}</value> -->
		<!-- </property> -->
		<!-- <property name="username"> -->
		<!-- <value>${jdbc_username}</value> -->
		<!-- </property> -->
		<!-- <property name="password"> -->
		<!-- <value>${jdbc_password}</value> -->
		<!-- </property> -->
	</bean>
	<!-- 配置資料來源事務管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
		<!-- 引用上面的資料來源 -->
	</bean>

	<!-- 自動掃描了所有的XxxxMapper.xml對應的mapper介面檔案,這樣就不用一個一個手動配置Mpper的映射了,只要Mapper介面類和Mapper對映檔案對應起來就可以了。 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.travesky.bluesky.activiti.dao" />
	</bean>
	<!-- 配置Mybatis的檔案 ,mapperLocations配置**Mapper.xml檔案位置,configLocation配置mybatis-config檔案位置-->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mapperLocations" value="classpath*:com/travesky/bluesky/activiti/mapper/**/*.xml"/>
		<property name="configLocation" value="classpath:mybatis/mybatis-cfg.xml" />
	</bean>

	<!-- 自動掃描註解的bean -->
	<context:component-scan base-package="com.travesky.bluesky.activiti.service" />
	<!-- spring 整合mybaitis end -->

	<!-- activiti begin -->
	<!-- 配置流程引擎配置類 注意:這是用 org.activiti.spring.SpringProcessEngineConfiguration 這個類-->
	<bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration">
		<property name="dataSource" ref="dataSource"/>
		<property name="transactionManager" ref="transactionManager" />
		<property name="databaseSchemaUpdate" value="true" />
		<property name="jobExecutorActivate" value="false" />
		<property name="createDiagramOnDeploy" value="true" />
		<!-- 是否生成流程定義圖片 -->
		<!-- 生成流程圖的字型不設定會亂碼 -->
		<property name="activityFontName" value="宋體"/>
		<property name="labelFontName" value="宋體"/>
	</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="managementService" factory-bean="processEngine" factory-method="getManagementService" />
	<!-- activiti end -->
</beans>

-----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對映檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.travesky.bluesky.activiti.dao.UserDao">
	<!--設定domain類和資料庫中表的欄位一一對應,注意資料庫欄位和domain類中的欄位名稱不致,此處一定要!-->
	<resultMap id="BaseResultMap" type="com.travesky.bluesky.activiti.domain.User">
		<id column="USER_ID" property="userId" jdbcType="INTEGER" />
		<result column="USER_NAME" property="userName" jdbcType="CHAR" />
		<result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />
		<result column="USER_EMAIL" property="userEmail" jdbcType="CHAR" />
	</resultMap>
	<!-- 查詢單條記錄 -->
	<select id="selectUserById" parameterType="int" resultMap="BaseResultMap">
		SELECT * FROM t_user WHERE USER_ID = #{userId}
	</select>
</mapper>

---建立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<Task> taskList = taskService.createTaskQuery().processDefinitionId(processDefinition.getId()).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<Task> tasks = taskService.createTaskQuery().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<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstance.getId()).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<String> candidateUsers = new ArrayList<String>();
		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的資料庫,在執行完後會自動建立表。

到這裡配置好spring+activiti+mybatis+mysql!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

=====================================================

這裡開始新增spirngMVC,並轉換maven工程為web專案

接上面的工程接著說,此時要加spingMVC之前,工程得再稍微轉換下

此時webapp下的結果還沒有顯示出來,因為此時我們還沒有配置此的專案為web專案

再次進去Properties配置,如下圖所示:如果沒有顯示如下,那就先把dynamic web module的√給去掉,然後重新再開啟 這個

進入,然後輸入如下內容

確定OK之後,webapp下面就會自動生成一些檔案,如下

--------配置SpringMVC

    --pom檔案需要新增兩個配置,上面我已經做了解釋,在貼一下

<!-- spring MVC 在轉換為web專案後新增的begin -->
<!-- javaee-api包 注意和專案使用的JDK版本對應 -->
<dependency>
	<groupId>javax</groupId>
	<artifactId>javaee-api</artifactId>
	<version>7.0</version>
	<scope>provided</scope>
</dependency>

<!-- javaee-web-api包 注意和專案使用的JDK版本對應 -->
<dependency>
	<groupId>javax</groupId>
	<artifactId>javaee-web-api</artifactId>
	<version>7.0</version>
	<scope>provided</scope>
</dependency>

----- 在src/main/resource中新增springmvc資料夾,然後新增檔案spring-mvc.xml,內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p"
	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">

	<!-- 掃描controller(controller層注入) -->
	<context:component-scan base-package="com.travesky.bluesky.activiti.controller"/>

	<!-- 對模型檢視新增前後綴 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/view/" p:suffix=".jsp"/>
</beans>

-----配置web,xml

----web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

	<display-name>activiti</display-name>
	<!-- 起始歡迎介面 -->
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 讀取spring配置檔案 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-activiti.xml</param-value>
	</context-param>
	<!-- 設計路徑變數值 -->
	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>springmvc.root</param-value>
	</context-param>

	<!-- Spring字符集過濾器 -->
	<filter>
		<filter-name>SpringEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>SpringEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- 日誌記錄 -->
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	<context-param>
		<!-- 日誌配置檔案路徑 -->
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value>
	</context-param>
	<context-param>
		<!-- 日誌頁面的重新整理間隔 -->
		<param-name>log4jRefreshInterval</param-name>
		<param-value>6000</param-value>
	</context-param>

	<!-- springMVC核心配置 -->
	<servlet>
		<servlet-name>dispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<!--spingMVC的配置路徑 -->
			<param-value>classpath:springmvc/spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- 攔截設定 -->
	<servlet-mapping>
		<servlet-name>dispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- 錯誤跳轉頁面 -->
	<error-page>
		<!-- 路徑不正確 -->
		<error-code>404</error-code>
		<location>/WEB-INF/errorpage/404.jsp</location>
	</error-page>
	<error-page>
		<!-- 沒有訪問許可權,訪問被禁止 -->
		<error-code>405</error-code>
		<location>/WEB-INF/errorpage/405.jsp</location>
	</error-page>
	<error-page>
		<!-- 內部錯誤 -->
		<error-code>500</error-code>
		<location>/WEB-INF/errorpage/500.jsp</location>
	</error-page>
</web-app>

------

新增index.jsp

在src/main/webapp/WEB-INF下新建一個資料夾view,新增一個index.jsp,內容如下:

<%@ 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執行專案了

接下來控制檯就會列印日誌出來了!如下

列印瀏覽器,輸入網址:http://localhost:8088/activiti/