SpringBoot2整合activiti7

目录

 

1、创建SpringBoot2 工程

2、引入 maven 依赖

3、主配置文件

4、创建数据库

5、主程序

6、测试程序,生成25张表

7、创建流程定义图

8、创建SpringSecurity工具类

9、创建SpringSecurity配置类

10、查看流程定义

 11、启动流程

12、查看并完成任务


1、创建SpringBoot2 工程

使用 idea,创建SpringBoot2 工程,坐标如下:

    com.example
    activiti-demo
    0.0.1-SNAPSHOT
    activiti-demo

2、引入 maven 依赖



    4.0.0

    com.example
    activiti-demo
    0.0.1-SNAPSHOT
    activiti-demo


    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.0.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            mysql
            mysql-connector-java
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
        
            org.activiti
            activiti-spring-boot-starter
            7.0.0.Beta2
        

        
            org.mybatis
            mybatis
            3.4.5
        
        
            mysql
            mysql-connector-java
            5.1.27
        


    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



3、主配置文件

spring:
  datasource:
    url: jdbc:mysql://124.70.178.21:3306/activiti?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
    username : root
    password : 
    driver-class-name: com.mysql.jdbc.Driver
  activiti:
    historyLevel: audit
    db-history-used: true

4、创建数据库

创建一个名为 activit 的数据库

5、主程序

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class ActivitiDemoApplication {

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

}

6、测试程序,生成25张表

@RunWith(SpringRunner.class)
@SpringBootTest
public class ActivitiDemoApplicationTests {
    
    @Test
    public void contextLoads() {
        

    }
}

注意:有的生成的是17张表,其中缺了历史表。如果是这样的话,见步骤3,里面有个配置是生成历史表的

7、创建流程定义图

创建 resources / processes / holiday.bpmn 文件,流程图如下:

SpringBoot2整合activiti7_第1张图片

具体内容:



  
    
    
    
    
    
    
    
    
    
  
  
    
      
        
        
          
        
      
      
        
        
          
        
      
      
        
        
          
        
      
      
        
        
          
        
      
      
        
        
          
        
      
      
        
        
        
          
        
      
      
        
        
        
          
        
      
      
        
        
        
          
        
      
      
        
        
        
          
        
      
    
  

8、创建SpringSecurity工具类

该工具类用于模拟用户登录

package com.example.demo;

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
public class SecurityUtil {

    @Autowired
    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");
        }

        SecurityContextHolder.setContext(new SecurityContextImpl(new Authentication() {
            @Override
            public Collection 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);
    }
}

9、创建SpringSecurity配置类

该配置类用于可以理解成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.example.demo;

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
public class DemoApplicationConfiguration extends WebSecurityConfigurerAdapter {

    private Logger logger = LoggerFactory.getLogger(DemoApplicationConfiguration.class);

    @Override
    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailsService());
    }

    @Bean
    public UserDetailsService myUserDetailsService() {

        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();

        String[][] usersGroupsAndRoles = {
                {"zhangsan", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
                {"lishi", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
                {"wangwu", "password", "ROLE_ACTIVITI_USER", "GROUP_activitiTeam"},
                {"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 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
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

10、查看流程定义

    @Test
    public void contextLoads() {
        securityUtil.logInAs("zhangsan");
        Page processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 10));
        System.out.println("可用的流程定义数量:" + processDefinitionPage.getTotalItems());
        for (ProcessDefinition pd : processDefinitionPage.getContent()) {
            System.out.println("流程定义:" + pd);
        }
    }

 11、启动流程

    @Test
    public void testStartProcess() {
        securityUtil.logInAs("zhangsan");
        ProcessInstance pi = processRuntime.start(ProcessPayloadBuilder.start().withProcessDefinitionKey("holiday")
                .build());
        System.out.println("流程实例ID:" + pi.getId());
    }

12、查看并完成任务

    /**
     * 查询任务,并完成自己的任务
     */
    @Test
    public void testTask() {
        securityUtil.logInAs("zhangsan");
        Page taskPage=taskRuntime.tasks(Pageable.of(0,10));
        if (taskPage.getTotalItems()>0) {
            for (Task task : taskPage.getContent()) {
                System.out.println(task);
                taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId()).build());
            }
        }

    }

注意:将这一步骤的登录名 zhangsan ,改成lishi 、wangwu就可以跑完整个流程

你可能感兴趣的:(activiti,activiti7,activiti整合)