SpringBoot整合Activiti7

Activiti7發佈正式版以後,它與SpringBoot2.x已經徹底支持整合開發。咱們能夠將Activiti7與SpringBoot整合開發的座標引入到工程中,從而達到SpringBoot支持Activti7整合。java

1.使用IDEA建立SpringBoot項目
在工程的pom.xml文件中引入相關的依賴,具體依賴以下所示mysql

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>activiti</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>activiti</name>
    <description>Demo project for Spring Boot</description>

    <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>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>

        <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>5.1.27</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.application.yml文件配置
爲了可以實現Activiti7生成的表放到Mysql數據庫中,須要在配置文件application.yml中添加相關的配置web

server:
  port: 8085
spring:
  application:
    name: spring-activiti
  datasource:
    url: jdbc:mysql://localhost:3306/activiti?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&nullCatalogMeansCurrent=true
    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
    #檢測歷史表是否存在
    db-history-used: true
    #記錄歷史等級 可配置的歷史級別有none, activity, audit, full
    history-level: full
    #校驗流程文件,默認校驗resources下的processes文件夾裏的流程文件
    check-process-definitions: false

3.添加SpringSecurity安全框架整合配置
Activiti7與SpringBoot整合後,默認狀況下,集成了SpringSecurity安全框架,這樣咱們就要去準備SpringSecurity整合進來的相關用戶權限配置信息spring

1)添加SecurityUtil類
爲了可以快速實現SpringSecurity安全框架的配置,所添加的一個組件。sql

@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中找到。數據庫

2)添加DemoApplicationConfig類
它的做用是爲了實現SpringSecurity框架的用戶權限的配置,這樣咱們就能夠在系統中使用用戶權限信息apache

@Configuration
public class DemoApplicationConfiguration {

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

    @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"},
                {"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();
    }

}

4)建立測試類安全

@SpringBootTest
@Slf4j
class ActivitiApplicationTests {

    @Autowired
    private ProcessEngine processEngine;

    /**
     * 流程定義的部署
     */
    @Test
    public void createDeploy() { 
        RepositoryService repositoryService = processEngine.getRepositoryService();

        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("diagram/holiday.bpmn")//添加bpmn資源
                .addClasspathResource("diagram/holiday.png")
                .name("請假申請單流程")
                .deploy(); 
                
        log.info("流程部署id:" + deployment.getName());
        log.info("流程部署名稱:" + deployment.getId());
    }
}

運行結果:
1.jpgmybatis

2.jpg

遇到的問題:
1)歷史表默認不會生成,需在application.yml中配置app

spring:
  activiti:
    #檢測歷史表是否存在
    db-history-used: true
    #記錄歷史等級 可配置的歷史級別有none, activity, audit, full
    history-level: full
相關文章
相關標籤/搜索