您的当前位置:首页正文

使用Gradle构建SpringBoot+Vue.js的API开

来源:华拓网

SpringBoot可以很方便的编写api作为后端微服务。
为了彻底前后端分离,我不再使用SpringBoot推荐的模板引擎Thymeleaf,而是使用Vue.js单页作为前端,Vue使用webpack构建并使用Gradle插件编译打包将生成的index.html和js与css资源输出到SpringBoot的resources目录下的static目录中。
一、开发环境
MacOS操作系统
JDK1.8.0
Gradle 4.1
Node.js v8.2.1
Vue CLI 2.8.2
IntelliJ IDEA ULTIMATE 2017.2



1.打开IDEA,选择使用Gradle构建项目,去除默认勾选的Java选项,点击Next。



2.填写GroupId与Artifactid和版本号,点击Next

3.选择使用本地的Gradle来构建项目,指定Gradle home目录,点击Next->Finish。

4.项目构建好后如图所示

5.我们对着api-boot项目右键,选择New->Module 新建模块

6.选择使用Gradle构建的Java模块,点击Next



7.填写项目名为 server,点击Next->Finish。



8.和步骤5类似,我们对着api-boot项目右键,选择New->Module 新建模块
使用Gradle来构建Web项目,点击Next。

9.填写项目名为web,点击Next->Finish



10.构建好的项目如图所示

api-boot为项目的根模块,他包含两个子模块,分别为server和web。
其中server模块我们使用SpringBoot来编写后端接口,
web模块我们使用webpack来构建Vue.js的前端应用。

二、编写项目

1.使用SpringBoot 2.0 来开发后台接口
打开server模块的build.gradle,将内容修改为如下配置

buildscript {
    ext {
        springBootVersion = '2.0.0.M4'
    }
    repositories {
        mavenCentral()
        maven { url "[https://repo.spring.io/snapshot](https://repo.spring.io/snapshot)" }
        maven { url "[https://repo.spring.io/milestone](https://repo.spring.io/milestone)" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

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

group 'com.lanshiqin'
version '1.0'
sourceCompatibility = 1.8

jar {
    baseName = 'server'
    version =  '1.0'
}

repositories {
    mavenCentral()
    maven { url "[https://repo.spring.io/snapshot](https://repo.spring.io/snapshot)" }
    maven { url "[https://repo.spring.io/milestone](https://repo.spring.io/milestone)" }
}

dependencies {
    compile project(':web')
    compile('org.springframework.boot:spring-boot-starter-web')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

在server模块的src/main/java目录下新建包和类



在server模块的src/main/resources目录下新建static目录,springBoot默认会在改路径下寻找静态资源,我们在static目录下新建index.html。
使用Java Application的方式运行SpringBoot项目,默认使用8080端口。



2.使用webpack来构建前端Vue.js
打开web模块的build.gradle,将内容修改为如下所示:
group 'com.lanshiqin'
version '1.0'

buildscript {
    repositories {
        maven {
            url "[https://plugins.gradle.org/m2/](https://plugins.gradle.org/m2/)"
        }
    }

    dependencies {
        classpath "com.moowork.gradle:gradle-node-plugin:1.2.0"
    }
}

apply plugin: 'com.moowork.node'
apply plugin: 'java'

//调用npm run build命令的Gradle任务
task npmBuild(type: NpmTask, dependsOn: npmInstall) {
    group = 'node'
    args = ['run', 'build']
}

//Gradle的java插件的jar任务,依赖npmBuild,即web子模块打jar包前必须运行npm run build
jar.dependsOn npmBuild

//调用npm run dev
task npmDev(type: NpmTask, dependsOn: npmInstall) {
    group = 'node'
    args = ['run', 'dev']
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

3.打开命令行终端,在其他目录下使用 vue init webpack web 来初始化vue项目



4.初始化后会在当前目录下生成web文件夹



将web文件夹内的所有文件和文件夹都拷贝到之前api-boot项目的web文件夹下。(注意要连同 点 . 开头的隐藏文件一起拷贝,因为一些配置文件 比如 ESlint就是点开头的,不拷贝后边运行项目就会报找不到ESLint配置文件的错误)

5.拷贝后的工程如图所示


6.在IDEA内部打开Terminal,cd web 切换到web模块下,执行 npm install。node包管理会自动下载所依赖的包到web目录下的node_modules文件夹下。

7.由于使用Gradle构建项目,构建出来的文件会在build文件夹下,这个和webpack构建的默认路径是一样的会冲突,所以我们需要修改webpack的build目录为其他。
将 api-boot/web/build目录改成script目录
修改 api-boot/web/package.json

"scripts": {
  "dev": "node build/dev-server.js",
  "start": "node build/dev-server.js",
  "build": "node build/build.js",
  "unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run",
  "e2e": "node test/e2e/runner.js",
  "test": "npm run unit && npm run e2e",
  "lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs"
},
修改成
"scripts": {
  "dev": "node script/dev-server.js",
  "start": "node script/dev-server.js",
  "build": "node script/build.js",
  "unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run",
  "e2e": "node test/e2e/runner.js",
  "test": "npm run unit && npm run e2e",
  "lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs"
},

修改 api-boot/web/script/webpack.dev.conf.js

Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
修改成
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
  baseWebpackConfig.entry[name] = ['./script/dev-client'].concat(baseWebpackConfig.entry[name])
})

修改api-boot/web/config/index.js

// see [http://vuejs-templates.github.io/webpack](http://vuejs-templates.github.io/webpack) for documentation.
var path = require('path')

var assetsRoot = path.resolve(__dirname, '../build/resources/main/static')// <-----1.添加

module.exports = {
  build: {
    env: require('./prod.env'),
    index: path.resolve(assetsRoot, 'index.html'),  // <-----2.修改
    assetsRoot: assetsRoot, // <-----3.修改
    assetsSubDirectory: 'assets', // <-----4.修改
    assetsPublicPath: '/',
    productionSourceMap: true,
    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],
    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  },
  dev: {
    env: require('./dev.env'),
    port: 3000, // <-----5.修改
    autoOpenBrowser: true,
    assetsSubDirectory: 'assets', // <-----6.修改
    assetsPublicPath: '/',
    proxyTable: { // <-----7.修改
      '/api/**': '[http://localhost:8080](http://localhost:8080)'//代理前台/api开头的请求,代理到8080端口,spring boot的访问端口
    },
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // 
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }
}

打开IDEA右侧的Gradle构建,展开api-boot下的web模块,展开Tasks->node
找到npmDev双击


随后会自动打开浏览器,端口为3000,Vue的js项目运行成功


三、项目打包

首先我们先看一下使用webpack管理的web模块。
由于我们已经在web模块下的build.gradle配置文件中配置好了node命令的gradle插件,
我们可以直接IDEA右侧的gradle打包,双击 api-boot根目录下的:web->Tasks->node->
npmBuild。
可以看到web目录下多了build文件夹,这个就是node构建输出的文件。

在server模块下的build.gradle文件中,我们配置了
compile project(':web’)


gradle在build server模块的时候会先将web模块打包成jar包作为依赖添加到server中。

双击 Gradle构建工程中的的 api-boot->server->Tasks->build->build
会在server模块下生成build文件夹,server/build/libs/server-1.0.jar就是打包的可执行jar包

切换到jar包所在的目录,执行 java -jar server-1.0.jar 回车,运行SpringBoot程序


可以看到控制台日志输出 Tomcat started on port(s): 8080 (http),表示运行成功
允许的端口为8080

打开浏览器,输入

发现vue打的jar包已经作为依赖jar并成功添加到所配置的resource/static目录下。
整合到此完毕。
本项目开源地址:

欢迎点赞打赏关注