美文网首页
在Spring中使用flowable

在Spring中使用flowable

作者: Acamy丶 | 来源:发表于2018-08-25 20:13 被阅读0次

在上一篇文章(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中使用flowable

      本文链接:https://www.haomeiwen.com/subject/gdwgiftx.html