idea gradle+springboot2.0+mybatis+activiti 构建多项目 运行 打包

声明:本文是springboot2.0的多项目构建,springboot2.0和spingboot1.5的配置是有出入的,构建项目之前请规范您的springboot版本,选择2.0以上。

一、在IDEA中使用工具创建SpringBoot + Gradle的父工程

       new -> project ->gradle

二、在父工程下新建叁个模块 dao service web

       右键单击父工程 new -> module -> Spring Initializr -> type选项选中Gradle Project(其他视情况填写)

       创建module的最后一步要注意,子模块最好在父工程的目录下,避免不必要的麻烦

创建每个模块的时候 有一个让你选择加载jar包的过程 你可以选也可以不选 我建议什么都不用 项目创建完毕 根据项目需求 手动在build.gradle目录下加入你需要的jar包

 

三、以此类推创建service模块和web模块 作为项目的子模块

四、重要的事情说三遍(很重要)

修改父项目 也就是sys(第一个创建的gradle项目)下的setting.gradle文件,加入

include 'dao','service',"web" 
此代码表示 dao ,service ,web 这三个项目是他的子项目 如果不加入 后面在父项目中定义的所有规范将毫无意义

五、父项目下bulid.gradle代码

allprojects {
    apply plugin: 'java'
    apply plugin: 'idea'
    group = 'com.huyuqiang'
    version = '0.0.1-SNAPSHOT'
    //jvm(java虚拟机版本号)第一个是你项目使用的jdk版本 第二个是你项目运行的jdk版本
    sourceCompatibility = 1.8
    targetCompatibility = 1.8
}


subprojects {
    ext {
        //版本号定义
        springBootVersion = '2.0.3.RELEASE'
    }
    // java编译的时候缺省状态下会因为中文字符而失败
    [compileJava, compileTestJava, javadoc]*.options*.encoding = 'UTF-8'
    repositories {
        mavenLocal()
        maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
        maven { url "https://repo.spring.io/libs-release" }
        mavenCentral()
        jcenter()
    }
    configurations {
        all*.exclude module: 'commons-logging'
    }
}
//定义子项目dao的配置
project(':dao') {
    dependencies {
        compile(
                //redis缓存框架随便加的 自己项目中需要什么加什么
                'org.springframework.boot:spring-boot-starter-data-redis'
                //'org.springframework.boot:spring-boot-starter-jdbc',
                //'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2'
        )
        testCompile(
                'org.springframework.boot:spring-boot-starter-test',
                "junit:junit:4.12"
        )
    }

}
//定义子项目service的配置
project(':service') {
    dependencies {
        //service依赖于dao
        compile project(":dao")
        compile(
                'org.springframework.boot:spring-boot-starter-web',
        )
        testCompile(
                'org.springframework.boot:spring-boot-starter-test',
                "junit:junit:4.12"
        )
    }

}
project(':web') {
    apply plugin: "war"
    dependencies {
        //web依赖于service
        compile project(":service")
        compile(
                'org.springframework.boot:spring-boot-starter-web'
        )
        testCompile(
                'org.springframework.boot:spring-boot-starter-test',
                "junit:junit:4.12"
        )
//        providedCompile(
//                "javax.servlet:javax.servlet-api:3.1.0",
//                "javax.servlet.jsp:jsp-api:2.2.1-b03",
//                "javax.servlet.jsp.jstl:javax.servlet.jsp.jstl-api:1.2.1"
//        )
    }
    processResources{
        /* 从'$projectDir/src/main/java'目录下复制文件到'WEB-INF/classes'目录下覆盖原有同名文件*/
        from("$projectDir/src/main/java")
    }

    /*自定义任务用于将当前子项目的java类打成jar包,此jar包不包含resources下的文件*/
    def jarArchiveName="${project.name}-${version}.jar"
    task jarWithoutResources(type: Jar) {
        from sourceSets.main.output.classesDir
        archiveName jarArchiveName
    }

    /*重写war任务:*/
    war {
        dependsOn jarWithoutResources
        /* classpath排除sourceSets.main.output.classesDir目录,加入jarWithoutResources打出来的jar包 */
        classpath = classpath.minus(files(sourceSets.main.output.classesDir)).plus(files("$buildDir/$libsDirName/$jarArchiveName"))
    }
    /*打印编译运行类路径*/
    task jarPath << {
        println configurations.compile.asPath
    }
}
/*从子项目拷贝War任务生成的压缩包到根项目的build/explodedDist目录*/
task explodedDist(type: Copy) {
    into "$buildDir/explodedDist"
    subprojects {
        from tasks.withType(War)
    }
}

六、子项目dao中bulid.gradle代码

buildscript {
    ext {
        springBootVersion = '2.0.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.huyuqiang'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenLocal()
    maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
    maven { url "https://repo.spring.io/libs-release" }
    mavenCentral()
    jcenter()
}


dependencies {
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

七、子项目service中bulid.gradle代码

buildscript {
    ext {
        springBootVersion = '2.0.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.huyuqiang'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenLocal()
    maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
    maven { url "https://repo.spring.io/libs-release" }
    mavenCentral()
    jcenter()
}


dependencies {
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

八、子项目web中bulid.gradle代码

buildscript {
    ext {
        springBootVersion = '2.0.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'war'

group = 'com.huyuqiang'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenLocal()
    maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
    maven { url "https://repo.spring.io/libs-release" }
    mavenCentral()
    jcenter()
}

configurations {
    providedRuntime
}

dependencies {
    providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
}

九、在web子模块下创建controller文件夹,文件夹下创建一个controller类,请看清楚我截图的包结构,如果包结构不对,启动项目的时候访问网页会报错(Whiteable Error Page) ),这是springboot有默认的包结构,如果你的包结构不对spring启动的时候是找不到

你的controller类的

启动web子模块包下的的webapplication启动类,访问localhost:8080

重要提示:

如果你在项目中加入了data框架引用 例如 mybatis jdbc 等 你在第一次启动项目的时候如果没有配置数据源,tomcat会报错无法启动,提示你需要配置数据源。

十、打包:

            在父工程目录下输入命令 gradle build

       取出 web子模块下 build -> libs -> web-1.0.jar 

        java -jar 执行即可访问

十一、整合mybatis

  逆向工程 

 一、添加配置文件

新建一个空的XML配置文件,这里以generatorConfig.xml为名,放在resources目录下mybatis文件中,没有mybatis文件夹自己建一个,顺便创建一个mapper文件夹等下要用来放xm映射文件。具体内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <commentGenerator>
            <property name="suppressAllComments" value="true"></property>
            <property name="suppressDate" value="true"></property>
            <property name="javaFileEncoding" value="utf-8"/>
        </commentGenerator>

        <jdbcConnection driverClass="${driverClass}"
                        connectionURL="${connectionURL}"
                        userId="${userId}"
                        password="${password}">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <javaModelGenerator targetPackage="${modelPackage}" targetProject="${src_main_java}">
            <property name="enableSubPackages" value="true"></property>
            <property name="trimStrings" value="true"></property>
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="${sqlMapperPackage}" targetProject="${src_main_resources}" >
            <property name="enableSubPackages" value="true"></property>
        </sqlMapGenerator>

        <javaClientGenerator targetPackage="${mapperPackage}" targetProject="${src_main_java}" type="XMLMAPPER">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- sql占位符,表示所有的表 -->
        <table tableName="%">
        </table>
    </context>
</generatorConfiguration>

创建一个gradle.properties文件 代码如下:

# JDBC 驱动类名
jdbc.driverClassName=com.mysql.jdbc.Driver
# JDBC URL: jdbc:mysql:// + 数据库主机地址 + 端口号 + 数据库名
jdbc.url=jdbc:mysql://10.0.0.88:3306/taotaodb?useUnicode=true&amp;characterEncoding=utf8
# JDBC 用户名及密码
jdbc.username=root
jdbc.password=huyuqiang
# 生成实体类所在的包
package.model=com.huyuqiang.po
# 生成 mapper 类所在的包
package.mapper=com.huyuqiang.dao
# 生成 mapper xml 文件所在的包
package.xml=mapper

注意文件路径结构:

bulid.gradle文件代码如下:

//逆向工程方法
configurations {
    mybatisGenerator
}

dependencies {
    //逆向工程jar包
    mybatisGenerator 'org.mybatis.generator:mybatis-generator-core:1.3.2'
    mybatisGenerator 'mysql:mysql-connector-java:5.1.38'
    mybatisGenerator 'tk.mybatis:mapper:3.3.1'
    testCompile('org.springframework.boot:spring-boot-starter-test')
}


def getDbProperties = {
    def properties = new Properties()
    file("src/main/resources/mybatis/gradle.properties").withInputStream { inputStream ->
        properties.load(inputStream)
    }
    properties
}
//建立task并应用ant
task mybatisGenerate << {
    def properties = getDbProperties()
    ant.properties['targetProject'] = projectDir.path
    ant.properties['driverClass'] = properties.getProperty("jdbc.driverClassName")
    ant.properties['connectionURL'] = properties.getProperty("jdbc.url")
    ant.properties['userId'] = properties.getProperty("jdbc.username")
    ant.properties['password'] = properties.getProperty("jdbc.password")
    ant.properties['src_main_java'] = sourceSets.main.java.srcDirs[0].path
    ant.properties['src_main_resources'] = sourceSets.main.resources.srcDirs[0].path
    ant.properties['modelPackage'] = properties.getProperty("package.model")
    ant.properties['mapperPackage'] = properties.getProperty("package.mapper")
    ant.properties['sqlMapperPackage'] = properties.getProperty("package.xml")
    ant.taskdef(
            name: 'mbgenerator',
            classname: 'org.mybatis.generator.ant.GeneratorAntTask',
            classpath: configurations.mybatisGenerator.asPath
    )
    ant.mbgenerator(overwrite: true,
            configfile: 'src/main/resources/mybatis/generatorConfig.xml', verbose: true) {
        propertyset {
            propertyref(name: 'targetProject')
            propertyref(name: 'userId')
            propertyref(name: 'driverClass')
            propertyref(name: 'connectionURL')
            propertyref(name: 'password')
            propertyref(name: 'src_main_java')
            propertyref(name: 'src_main_resources')
            propertyref(name: 'modelPackage')
            propertyref(name: 'mapperPackage')
            propertyref(name: 'sqlMapperPackage')
        }
    }
}

gradle重建一下,Tasks下的other中会出现mybatiGenerate

右键run,完成逆向工程。

1.父项目build.gradle文件里定义dao模块处添加依赖

project(':dao') {
    dependencies {
        compile(
                //redis缓存框架随便加的 自己项目中需要什么加什么
                'org.springframework.boot:spring-boot-starter-data-redis',
                //jdbc
                'org.springframework.boot:spring-boot-starter-jdbc',
                //mybatis
                'org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2',
                //阿里巴巴连接池
                'com.alibaba:druid-spring-boot-starter:1.1.0',
                'mysql:mysql-connector-java:5.1.38'
        )
        testCompile(
                'org.springframework.boot:spring-boot-starter-test',
                "junit:junit:4.12"
        )
    }

}

2.web子项目模块resources文件夹下applicationproperties文件加入以下内容,也可以不用properties文件,用yml文件,yml文件的格式会让人感觉很舒服,这里我就不多说了差距不大:

spring.datasource.url=jdbc:mysql://10.0.0.8:3306/taotaodb?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=huyuqiang
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.initialSize=5  
spring.datasource.minIdle=5  
spring.datasource.maxActive=20  
spring.datasource.maxWait=60000  

3.java配置代替传统的xml配置

创建一个类,此处名为mybatiConfig目录如下:

代码如下:

package com.huyuqiang.web.tools;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration
/*告诉spring mybatis生成的dao所在的位置*/
@MapperScan("com.huyuqiang.dao")
public class mybatisConfig {
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        ///告诉spring mybatis生成的mapper.xml所在的位置
        sqlSessionFactoryBean.setMapperLocations(resolver
                .getResources("classpath:/mapper/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    //配置druid阿里的连接池
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource dataSource() {
        return new DruidDataSource();
    }
}

注:scanBasePackages = "com.huyuqiang.*" 启动的时候

@SpringBootApplication 只会扫描当前包下的文件 因为是多模块项目 springboot并不知道你的service在什么地方,所以必须加。
@SpringBootApplication(scanBasePackages = "com.huyuqiang.*")
public class WebApplication {

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

启动web子模块包下的的webapplication启动类,访问localhost:8080。

十二:整合activiti

我整合是把activiti生成的28张表和项目数据库的表放在一个数据库中

至于如何分开放在两个数据库中,说实在的能不能做到,可以,无非是两个数据源,配置多数据源切换 

多数据源的切换springboot不是不能做,实现起来也不难,可是用起来就很不舒服,而且在管理事物上也

会出现问题,事物无法同步,其实我还是觉得多数据源这种问题尽量不要在spring中解决 还是应该放到

数据库那边 交给dba做分布式来的比较舒服,也更加正统,毕竟我是做代码层的,数据库仅限于一些sql

语言,对分布式等一些数据库层的定义语言知之甚少 也不敢妄自菲薄 只是说一下个人感想 

言归正传 看看springboot2.0和activiti6.0的整合

 父项目build.gradle加入jar包依赖

'org.activiti:activiti-spring-boot-starter-basic:6.0.0'

web子模块resources文件夹下创建文件夹processes文件夹,里面放入一个需要部署的bpmn流程文件,因为项目启动的时候springboot会去加载这个文件夹下的bpmn文件

完成自动部署

如果没有就会报错 如果不想让springboot自动部署流程

 application.properties文件里加入一下两行代码:

spring.activiti.check-process-definitions=false
spring.activiti.database-schema-update=true


webapplication启动类里面代码如下

@SpringBootApplication(scanBasePackages = "com.huyuqiang.*",exclude = SecurityAutoConfiguration.class)
public class WebApplication {

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


}

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)

剔除安全检查类,这个代码必须有不然会报一个“Error creating bean with name 'requestMappingHandlerMapping'”的错误

好了 就这么简单搞定了 启动直接可以用。
原文地址:https://www.cnblogs.com/woshuyuqiang/p/9276761.html