Activiti7整合SpringBoot(十二)
1 SpringBoot整合 Activiti7 的配置
为了能够实现 SpringBoot 与 Activiti7 整合开发,首先我们要引入相关的依赖支持。
所以,我们在工程的 pom.xml 文件中引入相关的依赖,具体依赖如下所示:
<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-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.activiti/activiti-spring-boot-starter -->
<dependency>
<groupId>org.activiti</groupId>
<artifactId>activiti-spring-boot-starter</artifactId>
<version>7.0.0.Beta2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
通过该 pom.xml 文件所导入的坐标,我们就可以实现 activiti7 与 Springboot 整合。
2 SpringBoot 的 application.yml 文件配置
为了能够实现 Activiti7 生成的表放到 Mysql 数据库中,需要在 springboot 的配置文件 application.yml
中添加相关的配置
spring: datasource:
url: jdbc:mysql://localhost:3306/activiti?useUnicode=true
&characterEncoding=utf8&serverTimezone=GMT username : root
password : 123456
driver-class-name: com.mysql.jdbc.Driver
3添加 SpringSecurity 安全框架整合配置
因为 Activiti7 与 SpringBoot 整合后,默认情况下,集成了 SpringSecurity 安全框架,这样我们就要去
准备 SpringSecurity 整合进来的相关用户权限配置信息。
可以查看一下整合 SpringBoot 的依赖包,发现同时也将 SpringSecurity 的依赖包也添加进项目中了,
如下:
3.1 添加 SecurityUtil 类
添加 SecurityUtil 类。
为了能够快速实现 SpringSecurity 安全框架的配置,所添加的一个组件。
package com.topcheer.activiti;import org.springframework.beans.factory.annotation.Autowired;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
publicclass SecurityUtil { @Autowired
private UserDetailsService userDetailsService;publicvoid logInAs(String username) { UserDetails user
= userDetailsService.loadUserByUsername(username);if (user == null) {thrownew IllegalStateException("User " + username + " doesn't exist, please provide a valid user"); }
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
publicboolean isAuthenticated() {returntrue; }
@Override
publicvoid setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { }
@Override
public String getName() {return user.getUsername(); }
}));
org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(username);
}
}
这个类可以从我们下载的 Activiti7 官方提供的 Example 中找到。
3.2 添加 DemoApplicationConfig 类
在 Activiti7 官方下载的 Example 中找到 DemoApplicationConfig 类,它的作用是为了实现
SpringSecurity 框架的用户权限的配置,这样我们就可以在系统中使用用户权限信息。本次项目中基
本是在文件中定义出来的用户信息,当然也可以是数据库中查询的用户权限信息。
/* * Copyright 2018 Alfresco, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
http://www.apache.org/licenses/LICENSE-2.0 *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/package com.topcheer.activiti;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
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
@EnableWebSecurity
publicclass DemoApplicationConfiguration extends WebSecurityConfigurerAdapter {
private Logger logger = LoggerFactory.getLogger(DemoApplicationConfiguration.class);
@Override
@Autowired
publicvoid configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService());
}
@Bean
public UserDetailsService myUserDetailsService() {
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
String[][] usersGroupsAndRoles = {
{"salaboy", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
{"ryandawsonuk", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
{"erdemedeiros", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
{"other", "password", "ROLE_ACTIVITI_USER", "GROUP_otherTeam"},
{"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;
}
@Override
protectedvoid configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
returnnew BCryptPasswordEncoder();
}
}
4 使用 SpringBoot 整合 Junit 方式测试新特性
@RunWith(SpringRunner.class)@SpringBootTest
publicclass ActivitiApplicationTests { @Autowired
private ProcessRuntime processRuntime; @Autowired
private TaskRuntime taskRuntime; @Autowired
private SecurityUtil securityUtil;//// /**
// * 查看流程定义
// */
@Test
publicvoid contextLoads() {
securityUtil.logInAs("salaboy");
Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 10));
System.out.println("可用的流程定义数量:" + processDefinitionPage.getTotalItems());
for (ProcessDefinition pd : processDefinitionPage.getContent()) {
System.out.println("流程定义:" + pd);
}
}
//
// /**
// * 启动流程实例
// */
@Test
publicvoid testStartProcess() {
securityUtil.logInAs("salaboy");
ProcessInstance pi = processRuntime.start(ProcessPayloadBuilder.start().withProcessDefinitionKey("myProcess_1")
.build());
System.out.println("流程实例ID:" + pi.getId());
//流程实例ID:6d2a9bc1-0cee-11ea-acf5-f894c25ebadd
}
//
/**
* 查询任务,并完成自己的任务
*/
@Test
publicvoid testTask() {
securityUtil.logInAs("ryandawsonuk"); //指定用户认证信息
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());
}
//任务:TaskImpl{id='6d310464-0cee-11ea-acf5-f894c25ebadd', owner='null', assignee='null', name='first', description='null', createdDate=Fri Nov 22 14:07:56 CST 2019, claimedDate=null, dueDate=null, priority=50, processDefinitionId='myProcess_1:1:7f72b399-0cec-11ea-8c61-f894c25ebadd', processInstanceId='6d2a9bc1-0cee-11ea-acf5-f894c25ebadd', parentTaskId='null', status=CREATED}
//任务:[TaskImpl{id='b3cecc85-0cf0-11ea-89ae-f894c25ebadd', owner='null', assignee='null', name='second', description='null', createdDate=Fri Nov 22 14:24:13 CST 2019, claimedDate=null, dueDate=null, priority=50, processDefinitionId='myProcess_1:1:7f72b399-0cec-11ea-8c61-f894c25ebadd', processInstanceId='6d2a9bc1-0cee-11ea-acf5-f894c25ebadd', parentTaskId='null', status=CREATED}]
}
}
Activiti 新的 API 介绍
https://github.com/Activiti/activiti-7-developers-guide/blob/51a1681c0e4bb5e2f96a6dea73516c9fd53d8521/getting-started/getting-started-activiti-core.md
以上是 Activiti7整合SpringBoot(十二) 的全部内容, 来源链接: utcz.com/z/509551.html