Flowable基础二十一 Flowable springboot 集成

Spring Boot


    Spring Boot是一个应用框架,按照官网的介绍,可以轻松地创建独立运行的,生产级别的,基于Spring的应用,并且可以“直接运行”。坚持使用Spring框架与第三方库,使你可以轻松地开始使用。大多数Spring Boot应用只需要很少的Spring配置

要获得更多关于Spring Boot的信息,请查阅http://projects.spring.io/spring-boot/

    Flowable与Spring Boot的集成目前是我们与Spring的提交者共同开发的。

1.1. 兼容性 Compatibility

Spring Boot需要JDK 7运行时环境。可以通过调整配置,在JDK6下运行。请查阅Spring Boot的文档。

1.2. 开始 Getting started

Spring Boot提倡约定大于配置。要开始工作,简单地在你的项目中添加spring-boot-starters-basic依赖。例如在Maven中:

<dependency>
	<groupId>org.flowable</groupId>
	<artifactId>flowable-spring-boot-starter-basic</artifactId>
	<version>${flowable.version}</version>
</dependency>

就这么简单。这个依赖会自动向classpath添加正确的Flowable与Spring依赖。现在你可以编写Spring Boot应用了:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Flowable需要数据库存储数据。如果你运行上面的代码,会得到提示性的异常信息,指出需要在classpath中添加数据库驱动依赖。现在添加H2数据库依赖:

<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<version>1.4.183</version>
</dependency>

应用这次可以启动了。你会看到类似这样的输出:

  .   ____          _            __ _ _  /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )   '  |____| .__|_| |_|_| |_\__, | / / / /  =========|_|==============|___/=/_/_/_/  :: Spring Boot ::        (v1.1.6.RELEASE) MyApplication                            : Starting MyApplication on ... s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@33cb5951: startup date [Wed Dec 17 15:24:34 CET 2014]; root of context hierarchy a.s.b.AbstractProcessEngineConfiguration : No process definitions were found using the specified path (classpath:/processes/**.bpmn20.xml). o.flowable.engine.impl.db.DbSqlSession   : performing create on engine with resource org/flowable/db/create/flowable.h2.create.engine.sql o.flowable.engine.impl.db.DbSqlSession   : performing create on history with resource org/flowable/db/create/flowable.h2.create.history.sql o.flowable.engine.impl.db.DbSqlSession   : performing create on identity with resource org/flowable/db/create/flowable.h2.create.identity.sql o.a.engine.impl.ProcessEngineImpl        : ProcessEngine default created o.a.e.i.a.DefaultAsyncJobExecutor        : Starting up the default async job executor [org.flowable.spring.SpringAsyncExecutor]. o.a.e.i.a.AcquireTimerJobsRunnable       : {} starting to acquire async jobs due o.a.e.i.a.AcquireAsyncJobsDueRunnable    : {} starting to acquire async jobs due o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup MyApplication                            : Started MyApplication in 2.019 seconds (JVM running for 2.294)

只是在classpath中添加依赖,并使用@EnableAutoConfiguration注解,就会在幕后发生很多事情:

  • 自动创建了内存数据库(因为classpath中有H2驱动),并传递给Flowable流程引擎配置

  • 创建并暴露了Flowable ProcessEngine bean

  • 所有的Flowable服务都暴露为Spring bean

  • 创建了Spring Job Executor

并且,processes目录下的任何BPMN 2.0流程定义都会被自动部署。创建processes目录,并在其中创建示例流程定义(命名为one-task-process.bpmn20.xml):

<?xml version="1.0" encoding="UTF-8"?><definitions
        xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL"
        xmlns:flowable="http://flowable.org/bpmn"
        targetNamespace="Examples">

    <process id="oneTaskProcess" name="The One Task Process">
        <startEvent id="theStart" />
        <sequenceFlow id="flow1" sourceRef="theStart" targetRef="theTask" />
        <userTask id="theTask" name="my task" />
        <sequenceFlow id="flow2" sourceRef="theTask" targetRef="theEnd" />
        <endEvent id="theEnd" />
    </process>
</definitions>

然后添加下列代码,以测试部署是否生效。CommandLineRunner是一个特殊的Spring bean,在应用启动时执行:

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

    @Bean
    public CommandLineRunner init(final RepositoryService repositoryService,
                                  final RuntimeService runtimeService,
                                  final TaskService taskService) {

        return new CommandLineRunner() {
            @Override
            public void run(String... strings) throws Exception {
                System.out.println("Number of process definitions : "
                	+ repositoryService.createProcessDefinitionQuery().count());
                System.out.println("Number of tasks : " + taskService.createTaskQuery().count());
                runtimeService.startProcessInstanceByKey("oneTaskProcess");
                System.out.println("Number of tasks after process start: "
                   + taskService.createTaskQuery().count());
            }
        };
    }}

会得到这样的输出:

Number of process definitions : 1 
Number of tasks : 0
Number of tasks after process start : 1
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 添加依赖 在`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>org.flowable</groupId> <artifactId>flowable-spring-boot-starter</artifactId> <version>${flowable.version}</version> </dependency> ``` 2. 配置数据库 在`application.yml`文件中添加以下配置: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/flowable?useUnicode=true&characterEncoding=utf-8&useSSL=false username: root password: root driver-class-name: com.mysql.jdbc.Driver ``` 3. 配置流程引擎 在`application.yml`文件中添加以下配置: ```yaml flowable: database-schema-update: true history-level: full ``` 4. 自定义流程引擎配置 可以通过继承`ProcessEngineConfigurationConfigurer`接口来自定义流程引擎配置,例如: ```java @Configuration public class FlowableConfig { @Bean public ProcessEngineConfigurationConfigurer processEngineConfigurationConfigurer() { return processEngineConfiguration -> { processEngineConfiguration.setAsyncExecutorActivate(false); processEngineConfiguration.setActivityFontName("宋体"); processEngineConfiguration.setLabelFontName("宋体"); }; } } ``` 5. 编写流程定义 在`src/main/resources/processes`目录下创建流程定义文件,例如`leave.bpmn20.xml`: ```xml <?xml version="1.0" encoding="UTF-8"?> <definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" targetNamespace="http://www.flowable.org/processdef"> <process id="leave" name="请假流程" isExecutable="true"> <startEvent id="start" name="开始"/> <userTask id="apply" name="申请请假"> <extensionElements> <flowable:formProperty id="reason" name="请假原因" type="string" required="true"/> <flowable:formProperty id="days" name="请假天数" type="long" required="true"/> </extensionElements> <documentation>请假申请节点,需要填写请假原因和请假天数</documentation> <incoming>startToApply</incoming> <outgoing>applyToApprove</outgoing> <potentialOwner> <resourceAssignmentExpression> <formalExpression>applyer</formalExpression> </resourceAssignmentExpression> </potentialOwner> </userTask> <userTask id="approve" name="审批"> <extensionElements> <flowable:formProperty id="result" name="审批结果" type="enum" required="true"> <flowable:value id="pass" name="通过"/> <flowable:value id="reject" name="驳回"/> </flowable:formProperty> <flowable:formProperty id="comment" name="审批意见" type="string" required="false"/> </extensionElements> <documentation>审批节点,需要填写审批结果和审批意见</documentation> <incoming>applyToApprove</incoming> <outgoing>approveToEnd</outgoing> <potentialOwner> <resourceAssignmentExpression> <formalExpression>approver</formalExpression> </resourceAssignmentExpression> </potentialOwner> </userTask> <endEvent id="end" name="结束"> <incoming>approveToEnd</incoming> </endEvent> <sequenceFlow id="startToApply" sourceRef="start" targetRef="apply"/> <sequenceFlow id="applyToApprove" sourceRef="apply" targetRef="approve"/> <sequenceFlow id="approveToEnd" sourceRef="approve" targetRef="end"/> </process> <bpmndi:BPMNDiagram> <bpmndi:BPMNPlane bpmnElement="leave"> <bpmndi:BPMNShape id="start_shape" bpmnElement="start"> <omgdc:Bounds x="180" y="80" width="50" height="50"/> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="apply_shape" bpmnElement="apply"> <omgdc:Bounds x="250" y="60" width="100" height="80"/> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="approve_shape" bpmnElement="approve"> <omgdc:Bounds x="400" y="60" width="100" height="80"/> </bpmndi:BPMNShape> <bpmndi:BPMNShape id="end_shape" bpmnElement="end"> <omgdc:Bounds x="550" y="80" width="50" height="50"/> </bpmndi:BPMNShape> <bpmndi:BPMNEdge id="startToApply_edge" bpmnElement="startToApply"> <omgdi:waypoint x="205" y="105"/> <omgdi:waypoint x="250" y="100"/> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="applyToApprove_edge" bpmnElement="applyToApprove"> <omgdi:waypoint x="350" y="100"/> <omgdi:waypoint x="400" y="100"/> </bpmndi:BPMNEdge> <bpmndi:BPMNEdge id="approveToEnd_edge" bpmnElement="approveToEnd"> <omgdi:waypoint x="500" y="100"/> <omgdi:waypoint x="550" y="105"/> </bpmndi:BPMNEdge> </bpmndi:BPMNPlane> </bpmndi:BPMNDiagram> </definitions> ``` 6. 编写流程服务 编写流程服务,例如: ```java @Service public class LeaveService { @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; public void startProcess(String applyer, String reason, long days) { Map<String, Object> variables = new HashMap<>(); variables.put("applyer", applyer); variables.put("reason", reason); variables.put("days", days); runtimeService.startProcessInstanceByKey("leave", variables); } public void approveTask(String taskId, String result, String comment) { Map<String, Object> variables = new HashMap<>(); variables.put("result", result); variables.put("comment", comment); taskService.complete(taskId, variables); } public List<Task> getTasks(String assignee) { return taskService.createTaskQuery().taskAssignee(assignee).list(); } } ``` 7. 测试流程服务 编写测试类,例如: ```java @SpringBootTest @RunWith(SpringRunner.class) public class LeaveServiceTest { @Autowired private LeaveService leaveService; @Test public void testLeaveProcess() { String applyer = "张三"; String reason = "生病了"; long days = 3; leaveService.startProcess(applyer, reason, days); List<Task> tasks = leaveService.getTasks("approver"); Assert.assertNotNull(tasks); Assert.assertEquals(1, tasks.size()); Task task = tasks.get(0); Assert.assertEquals(reason, task.getFormProperty("reason").getValue()); Assert.assertEquals(days, task.getFormProperty("days").getValue()); leaveService.approveTask(task.getId(), "pass", "同意"); tasks = leaveService.getTasks("approver"); Assert.assertEquals(0, tasks.size()); } } ``` 8. 运行应用程序 运行应用程序,访问http://localhost:8080/actuator/flowable,可以查看流程引擎的状态信息。 以上是集成FlowableSpringBoot的基本步骤。具体实现可能因应用场景和需求而异,需要根据实际情况进行调整和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值