在Spring中使用flowable

在上一篇文章(flowable流程引擎初體驗,完成一個請假流程)我們使用了命令窗口的方式體驗了一把flowable的基本使用,了解了流程定義、部署、啟動以及流程之間的流轉情況,可以看出來其非常簡單方便。在實際項目中我們肯定要將其進行整合,而flowable對Spring也是絕對支持的,本文就是講解如何在Spring中使用flowable。

1. flowable流程引擎API

在上一篇文章中可以看到很多操作都是通過xxService來調用,而這些Services又都是由ProcessEngine產生, ProcessEngine對象通過ProcessEngineConfiguration來配置。所以在使用Spring整合flowable之前,我們必須理清這些關系,如下圖所示:主要有一個配置文件,一個配置對象, 一個引擎對象,七大服務。

2. Spring中配置flowable

首先創建一個典型的Spring項目,引入Spring和flowable相關依賴。然后在spring配置文件中添加掃描包,屬性文件以及引入flowable.cfg.xml.如下:

    <context:component-scan base-package="com.hebaohua.workflow" />
    
    <context:property-placeholder location="classpath*:properties/*.properties"/>

    <import resource="flowable.cfg.xml"/>

src/main/resources/properties文件夾下創建數據庫配置文件db.properties:

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/flowable?useUnicode=true&zeroDateTimeBehavior=convertToNull
jdbc.user=root
jdbc.password=123456

src/main/resources下創建日志配置文件log4j.properties:

log4j.rootLogger=DEBUG, CA

log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern= %d{hh:mm:ss,SSS} [%t] %-5p %c %x - %m%n

接下來就是最關鍵的flowable.cfg.xml了,如下所示:

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

    <bean id="processEngineConfiguration"
          class="org.flowable.spring.SpringProcessEngineConfiguration">
        <property name="dataSource" ref="dataSource"/>
        <property name="transactionManager" ref="transactionManager"/>
        <property name="databaseSchemaUpdate" value="true"/>
        <property name="asyncExecutorActivate" value="false" />
    </bean>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="processEngine" class="org.flowable.spring.ProcessEngineFactoryBean">
        <property name="processEngineConfiguration" ref="processEngineConfiguration"/>
    </bean>

    <!-- 7大接口 -->
    <bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService"/>
    <bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService"/>    
    <bean id="identityService" factory-bean="processEngine" factory-method="getIdentityService"/>
    <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"/>
    <bean id="identityService" factory-bean="processEngine" factory-method="getIdentityService"/>
    <bean id="formService" factory-bean="processEngine" factory-method="getFormService" />
</beans>

啟動應用就能通過@Autowired注解來進行使用這七大接口了,真是方便。如下用一個測試類來進行一個基本操作的演示:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class FlowableTest {
    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ManagementService managementService;

    /**
     * 部署流程模型
     */
    @Test
    public void testDeploy(){
        Deployment deployment = repositoryService.createDeployment()
                .name("testDeploy")
                .addClasspathResource("flowable/servicetask-form.bpmn20.xml")
                .deploy();
        System.out.println("Deploy successfullly, deployId:" + deployment.getId() + "; deployName:" + deployment.getName());
    }

    /**
     * 查詢流程定義
     */
    @Test
    public void queryProcessDefinitionTest(){
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId("1") // 用上一步中的結果
                .singleResult();
        System.out.println("Found process definition : " + processDefinition.getName() + "; key:"  + processDefinition.getKey() + ";id:" + processDefinition.getId());
    }

    /**
     * 啟動流程
     */
    @Test
    public void startProcessInstanceTest(){
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("employee", "jack");
        variables.put("nrOfHolidays", 3);
        variables.put("description", "回家看看");
        ProcessInstance processInstance =
                runtimeService.startProcessInstanceByKey("serviceTaskTest", variables);

    }

    /**
     * 查詢并完成任務
     */
    @Test
    public void queryAndCompleteTask(){
        // 查詢
        List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("managers").list();
        System.out.println("You have " + tasks.size() + " tasks:");
        for (int i=0; i<tasks.size(); i++) {
            System.out.println((i+1) + ") " + tasks.get(i).getName());
        }

        // 選擇
        Task task = tasks.get(1);
        Map<String, Object> processVariables = taskService.getVariables(task.getId());
        System.out.println(processVariables.get("employee") + " wants " +
                processVariables.get("nrOfHolidays") + " of holidays. Do you approve this?");

        //完成
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("approved", true);
        taskService.complete(task.getId(), variables);
    }

    /**
     * 查詢歷史數據
     */
    @Test
    public void queryHistoryData(){
        List<HistoricActivityInstance> activities =
                historyService.createHistoricActivityInstanceQuery().processInstanceId("4")
                        .orderByHistoricActivityInstanceEndTime().asc()
                        .list();

        for (HistoricActivityInstance activity : activities) {
            System.out.println(activity.getActivityId() + " took "
                    + activity.getDurationInMillis() + " milliseconds");
            System.out.println("======================================");
        }
    }

}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,973評論 19 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,959評論 6 342
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong閱讀 22,584評論 1 92
  • 入門 介紹 Spring Boot Spring Boot 使您可以輕松地創建獨立的、生產級的基于 Spring ...
    Hsinwong閱讀 16,954評論 2 89
  • 這個世界已經有很多人和事會讓你失望,而最不應該的,就是自己還令自己失望。請記住,社會很殘酷,你要活得有溫度! ??...
    忍神閱讀 190評論 0 0