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'”的錯誤

好了 就這么簡單搞定了 啟動直接可以用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM