您好,登錄后才能下訂單哦!
這篇文章主要介紹“Activiti7與Spring及Spring Boot整合開發的方法是什么”,在日常操作中,相信很多人在Activiti7與Spring及Spring Boot整合開發的方法是什么問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Activiti7與Spring及Spring Boot整合開發的方法是什么”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
如下
<properties> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> </properties> <dependencies> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-engine</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-bpmn-model</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-bpmn-converter</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-json-converter</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-bpmn-layout</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>org.activiti.cloud</groupId> <artifactId>activiti-cloud-services-api</artifactId> <version>7.0.0.Beta1</version> </dependency> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.5.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.7.RELEASE</version> </dependency> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> </dependencies> <repositories> <repository> <id>alfresco</id> <name>Activiti Releases</name> <url>https://artifacts.alfresco.com/nexus/content/repositories/activiti-releases/</url> <releases> <enabled>true</enabled> </releases> </repository> </repositories>
在Activiti中核心類的是ProcessEngine流程引擎,與Spring整合就是讓Spring來管理ProcessEngine
通過org.activiti.spring.SpringProcessEngineConfiguration 與Spring整合方式來創建ProcessEngine對象。
創建spring與activiti的整合配置文件:activiti-spring.xml(名稱不固定)
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 數據源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/activiti"/> <property name="username" value="root"/> <property name="password" value="123456"/> <property name="maxActive" value="3"/> <property name="maxIdle" value="1"/> </bean> <!-- 工作流引擎配置bean --> <bean id="processEngineConfiguration" class="org.activiti.spring.SpringProcessEngineConfiguration"> <!-- 數據源 --> <property name="dataSource" ref="dataSource"/> <!-- 使用spring事務管理器 --> <property name="transactionManager" ref="transactionManager"/> <!-- 數據庫策略 --> <property name="databaseSchemaUpdate" value="drop-create"/> </bean> <!-- 流程引擎 --> <bean id="processEngine" class="org.activiti.spring.ProcessEngineFactoryBean"> <property name="processEngineConfiguration" ref="processEngineConfiguration"/> </bean> <!-- 資源服務service --> <bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService"/> <!-- 流程運行service --> <bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService"/> <!-- 任務管理service --> <bean id="taskService" factory-bean="processEngine" factory-method="getTaskService"/> <!-- 歷史管理service --> <bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService"/> <!-- 事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 傳播行為 --> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice> <!-- 切面,根據具體項目修改切點配置 <aop:config proxy-target-class="true"> <aop:advisor advice-ref="txAdvice" pointcut="execution(*com.itheima.service.impl..(..))"/> </aop:config>--> </beans>
databaseSchemaUpdate的取值內容:
flase: 默認值。activiti在啟動時,會對比數據庫表中保存的版本,如果沒有表或者版本不匹配,將拋出異常。(生產環境常用)
true: activiti會對數據庫中所有表進行更新操作。如果表不存在,則自動創建。(開發時常用)
create_drop: 在activiti啟動時創建表,在關閉時刪除表(必須手動關閉引擎,才能刪除表)。(單元測試常用)
drop-create: 在activiti啟動時刪除原來的舊表,然后在創建新表(不需要手動關閉引擎)。
/** 測試activiti與spring整合是否成功 **/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:activiti-spring.xml") public class ActivitiTest { @Autowired private RepositoryService repositoryService; @Test public void test01(){ System.out.println("部署對象:"+repositoryService); } }
下面我們一起來分析Activiti與Spring整合加載的過程。
1、加載activiti-spring.xml配置文件
2、加載SpringProcessEngineConfiguration對象,這個對象它需要依賴注入dataSource對象和transactionManager對象。
3、加載ProcessEngineFactoryBean工廠來創建ProcessEngine對象,而ProcessEngineFactoryBean工廠又需要依賴注入processEngineConfiguration對象。
4、processEngine對象來負責創建我們的Service對象,從而簡化Activiti的開發過程。
Activiti7發布正式版之后,它與SpringBoot2.x已經完全支持整合開發。
為了能夠實現SpringBoot與Activiti7整合開發,首先我們要引入相關的依賴支持。
在工程的pom.xml文件中引入相關的依賴,其中activiti的依賴是:activiti-spring-boot-starter。
具體依賴如下所示:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>org.activiti</groupId> <artifactId>activiti-spring-boot-starter</artifactId> <version>7.0.0.Beta2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
通過該pom.xml文件所導入的坐標,我們就可以實現activiti7與Springboot整合。
為了能夠實現Activiti7生成的表放到Mysql數據庫中,需要在配置文件application.yml中添加相關的配置
注意:activiti7默認沒有開啟數據庫歷史記錄,需要手動配置開啟
spring: datasource: url: jdbc:mysql:///activiti?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver activiti: #1.flase:默認值。activiti在啟動時,對比數據庫表中保存的版本,如果沒有表或者版本不匹配,將拋出異常 #2.true: activiti會對數據庫中所有表進行更新操作。如果表不存在,則自動創建 #3.create_drop: 在activiti啟動時創建表,在關閉時刪除表(必須手動關閉引擎,才能刪除表) #4.drop-create: 在activiti啟動時刪除原來的舊表,然后在創建新表(不需要手動關閉引擎) database-schema-update: true #檢測歷史表是否存在 activiti7默認沒有開啟數據庫歷史記錄 啟動數據庫歷史記錄 db-history-used: true #記錄歷史等級 可配置的歷史級別有none, activity, audit, full #none:不保存任何的歷史數據,因此,在流程執行過程中,這是最高效的。 #activity:級別高于none,保存流程實例與流程行為,其他數據不保存。 #audit:除activity級別會保存的數據外,還會保存全部的流程任務及其屬性。audit為history的默認值。 #full:保存歷史數據的最高級別,除了會保存audit級別的數據外,還會保存其他全部流程相關的細節數據,包括一些流程參數等。 history-level: full #校驗流程文件,默認校驗resources下的processes文件夾里的流程文件 check-process-definitions: false
package com.itheima; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ActApplication { public static void main(String[] args) { SpringApplication.run(ActApplication.class,args); } }
因為Activiti7與SpringBoot整合后,默認情況下,集成了SpringSecurity安全框架,這樣我們就要去準備SpringSecurity整合進來的相關用戶權限配置信息。
SpringBoot的依賴包已經將SpringSecurity的依賴包也添加進項目中。
為了能夠快速實現SpringSecurity安全框架的配置,所添加的一個組件。
package com.itheima.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Component; import java.util.Collection; @Component public class SecurityUtil { private Logger logger = LoggerFactory.getLogger(SecurityUtil.class); @Autowired @Qualifier("myUserDetailsService") private UserDetailsService userDetailsService; public void logInAs(String username) { UserDetails user = userDetailsService.loadUserByUsername(username); if (user == null) { throw new IllegalStateException("User " + username + " doesn't exist, please provide a valid user"); } logger.info("> Logged in as: " + username); SecurityContextHolder.setContext( new SecurityContextImpl( new Authentication() { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return user.getAuthorities(); } @Override public Object getCredentials() { return user.getPassword(); } @Override public Object getDetails() { return user; } @Override public Object getPrincipal() { return user; } @Override public boolean isAuthenticated() { return true; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { } @Override public String getName() { return user.getUsername(); } })); org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(username); } }
這個類可以從我們下載的Activiti7官方提供的Example中找到。
在Activiti7官方下載的Example中找到DemoApplicationConfig類,它的作用是為了實現SpringSecurity框架的用戶權限的配置,這樣我們就可以在系統中使用用戶權限信息。
本次項目中基本是在文件中定義出來的用戶信息,當然也可以是數據庫中查詢的用戶權限信息。
后面處理流程時用到的任務負責人,需要添加在這里
package com.itheima.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Configuration public class DemoApplicationConfiguration { private Logger logger = LoggerFactory.getLogger(DemoApplicationConfiguration.class); @Bean public UserDetailsService myUserDetailsService() { InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager(); //這里添加用戶,后面處理流程時用到的任務負責人,需要添加在這里 String[][] usersGroupsAndRoles = { {"jack", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"}, {"rose", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"}, {"tom", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"}, {"other", "password", "ROLE_ACTIVITI_USER", "GROUP_otherTeam"}, {"system", "password", "ROLE_ACTIVITI_USER"}, {"admin", "password", "ROLE_ACTIVITI_ADMIN"}, }; for (String[] user : usersGroupsAndRoles) { List<String> authoritiesStrings = Arrays.asList(Arrays.copyOfRange(user, 2, user.length)); logger.info("> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]"); inMemoryUserDetailsManager.createUser(new User(user[0], passwordEncoder().encode(user[1]), authoritiesStrings.stream().map(s -> new SimpleGrantedAuthority(s)).collect(Collectors.toList()))); } return inMemoryUserDetailsManager; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
Activiti7可以自動部署流程,前提是在resources目錄下,創建一個新的目錄processes,用來放置bpmn文件。
創建一個簡單的Bpmn流程文件,并設置任務的用戶組Candidate Groups。
Candidate Groups中的內容與上面DemoApplicationConfiguration類中出現的用戶組名稱要保持一致,可以填寫:activitiTeam 或者 otherTeam。
這樣填寫的好處:當不確定到底由誰來負責當前任務的時候,只要是Groups內的用戶都可以拾取這個任務
package com.itheima.test; import com.itheima.utils.SecurityUtil; import org.activiti.api.process.model.ProcessInstance; import org.activiti.api.process.model.builders.ProcessPayloadBuilder; import org.activiti.api.process.runtime.ProcessRuntime; import org.activiti.api.runtime.shared.query.Page; import org.activiti.api.runtime.shared.query.Pageable; import org.activiti.api.task.model.Task; import org.activiti.api.task.model.builders.TaskPayloadBuilder; import org.activiti.api.task.runtime.TaskRuntime; import org.activiti.engine.repository.ProcessDefinition; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class Actviti7DemoApplicationTests { @Autowired private ProcessRuntime processRuntime; @Autowired private TaskRuntime taskRuntime; @Autowired private SecurityUtil securityUtil; @Test public void testActBoot(){ System.out.println(taskRuntime); } /** * 查看流程定義 */ @Test public void contextLoads() { securityUtil.logInAs("system"); Page<org.activiti.api.process.model.ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 10)); System.out.println("可用的流程定義數量:" + processDefinitionPage.getTotalItems()); for (org.activiti.api.process.model.ProcessDefinition pd : processDefinitionPage.getContent()) { System.out.println("流程定義:" + pd); } } /** * 啟動流程實例 */ @Test public void testStartProcess() { securityUtil.logInAs("system"); ProcessInstance pi = processRuntime.start(ProcessPayloadBuilder. start(). withProcessDefinitionKey("myProcess"). build()); System.out.println("流程實例ID:" + pi.getId()); } /** **查詢任務,并完成自己的任務 **/ @Test public void testTask() { securityUtil.logInAs("jack"); Page<Task> taskPage=taskRuntime.tasks(Pageable.of(0,10)); if (taskPage.getTotalItems()>0){ for (Task task:taskPage.getContent()){ taskRuntime.claim(TaskPayloadBuilder. claim(). withTaskId(task.getId()).build()); System.out.println("任務:"+task); taskRuntime.complete(TaskPayloadBuilder. complete(). withTaskId(task.getId()).build()); } } Page<Task> taskPage2=taskRuntime.tasks(Pageable.of*(0,10)); if (taskPage2.getTotalItems()>0){ System.out.println("任務:"+taskPage2.getContent()); } } }
到此,關于“Activiti7與Spring及Spring Boot整合開發的方法是什么”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。