├── .gitignore ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── lombok.config ├── package-lock.json ├── package.json ├── settings.gradle ├── src ├── main │ ├── java │ │ └── com │ │ │ └── example │ │ │ ├── SpringVueSampleApplication.java │ │ │ ├── controller │ │ │ ├── RootController.java │ │ │ └── api │ │ │ │ └── ProductsController.java │ │ │ ├── exception │ │ │ └── NotFoundException.java │ │ │ ├── model │ │ │ └── Product.java │ │ │ ├── repository │ │ │ └── ProductRepository.java │ │ │ ├── request │ │ │ ├── AddProductRequest.java │ │ │ └── EditProductRequest.java │ │ │ └── response │ │ │ ├── BasicResponse.java │ │ │ ├── ProductCreateResponse.java │ │ │ ├── ProductDeleteResponse.java │ │ │ ├── ProductEditResponse.java │ │ │ ├── ProductGetResponse.java │ │ │ └── ProductListResponse.java │ ├── js │ │ ├── app.js │ │ ├── components │ │ │ └── App.vue │ │ ├── pages │ │ │ ├── Home.vue │ │ │ ├── NotFound.vue │ │ │ └── product │ │ │ │ ├── AddProduct.vue │ │ │ │ ├── DeleteProduct.vue │ │ │ │ ├── EditProduct.vue │ │ │ │ └── ListProduct.vue │ │ └── routes.js │ └── resources │ │ ├── application.yml │ │ └── templates │ │ └── index.ftlh └── test │ └── java │ └── com │ └── example │ └── SpringVueSampleApplicationTests.java └── webpack.config.js /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | /node_modules 4 | /.gradle/ 5 | /out/ 6 | /classes/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | nbproject/private/ 24 | build/ 25 | nbbuild/ 26 | dist/ 27 | nbdist/ 28 | .nb-gradle/ 29 | node_modules/ 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 目的 2 | 3 | サーバーサイドエンジニアが気軽に vue.js + spring-boot で SPA 開発するためにはどうしたらいいか、という話。 4 | 5 | 登場するコンポーネントは以下のものたち。 6 | 7 | * spring-boot(Java の web application framework) 8 | * webpack(複数の JS をくっつけたりします) 9 | * npm(js の package manager) 10 | * babel(ES2015 を昔ながらの JS に変換するのに使います) 11 | * vue.js(簡単便利な js frameworkで、弊社社内でメインで利用されてるやつ) 12 | 13 | ディレクトリ構造は以下のようにします。 14 | 15 | src/main/java/ ← java code 16 | src/main/js/ ← JS code 17 | build/resources/main/static/bundle.js ← 成果物 18 | 19 | 最終的には webpack の成果物が含まれる uber jar(fat jar ともいう)が `./gradlew build` で生成されるようにします。 20 | 21 | # セットアップ 22 | 23 | node.js を最新版にしてください。 24 | 25 | webpack をインストールします。 26 | 27 | npm install -g webpack 28 | 29 | まず、npm install で、package.json という npm の設定ファイルを生成します。 30 | 31 | npm install -y 32 | 33 | 開発時に必要なライブラリ・アプリケーションをインストールします。 34 | `--save-dev` オプションは、インストール後に package.json に開発時依存項目として追記するためのオプションです。 35 | 36 | npm install --save-dev webpack babel-core babel-preset-es2015 babel-loader \ 37 | vue-loader vue-style-loader vue-html-loader vue-template-compiler \ 38 | file-loader style-loader url-loader css-loader \ 39 | extract-text-webpack-plugin webpack 40 | 41 | vue.js, vue-router という、実行時に利用するライブラリをインストールします。 42 | `--save` オプションは、インストール後に package.json に依存項目として追記するためのオプションです。 43 | 44 | npm install --save vue bootstrap vue-router axios 45 | 46 | # webpack の設定 47 | 48 | webpack は JS/CSS 等の静的コンテンツを依存も含めて1つのファイルにまとめてくれるアプリケーションです。 49 | babel 等の前処理も webpack で呼び出します(babel は transpiler framework で、主に ES2015 を古いブラウザでも実行できるようにするために利用されています)。 50 | 51 | ExtractTextPlugin は、CSS ファイルを別ファイルとして書き出すために利用しています。 52 | 53 | ```javascript 54 | const webpack = require("webpack"); 55 | const ExtractTextPlugin = require("extract-text-webpack-plugin"); 56 | 57 | module.exports = { 58 | entry: './src/main/js/app.js', 59 | output: { 60 | filename: 'bundle.js', 61 | path: __dirname + '/build/resources/main/static' 62 | }, 63 | module: { 64 | loaders: [ 65 | { 66 | test: /\.vue$/, 67 | loader: 'vue-loader' 68 | }, 69 | { 70 | test: /\.js$/, 71 | use: 'babel-loader', 72 | exclude: /node_modules/ 73 | }, 74 | { 75 | test: /\.css$/, 76 | use: ExtractTextPlugin.extract({ 77 | fallback: "style-loader", 78 | use: "css-loader" 79 | }) 80 | }, 81 | // bootstrap に含まれる font 等を data url に変換する。 82 | {test: /\.svg$/, loader: 'url-loader?mimetype=image/svg+xml'}, 83 | {test: /\.woff$/, loader: 'url-loader?mimetype=application/font-woff'}, 84 | {test: /\.woff2$/, loader: 'url-loader?mimetype=application/font-woff'}, 85 | {test: /\.eot$/, loader: 'url-loader?mimetype=application/font-woff'}, 86 | {test: /\.ttf$/, loader: 'url-loader?mimetype=application/font-woff'} 87 | ] 88 | }, 89 | plugins: [ 90 | new ExtractTextPlugin("styles.css"), 91 | ] 92 | } 93 | ; 94 | ``` 95 | 96 | webpack は `webpack` コマンドを実行するだけで利用できます。 97 | 開発時には `webpack -w` とすると、プロセスが常駐し、ファイルの更新を監視して、更新があったらリビルドされるようになります。 98 | 99 | # gradle とのつなぎ込み 100 | 101 | webpack を実行する gradle task を設定します。 102 | `./gradlew build` した時に、uber jar の中に webpack の成果物を埋めるような設定を行います。 103 | 104 | ```groovy 105 | buildscript { 106 | repositories { 107 | mavenCentral() 108 | jcenter() 109 | } 110 | dependencies { 111 | classpath 'com.moowork.gradle:gradle-node-plugin:0.12' 112 | } 113 | } 114 | 115 | apply plugin: 'java' 116 | apply plugin: "com.moowork.node" 117 | 118 | node { 119 | version = '6.6.0' 120 | npmVersion = '3.10.7' 121 | download = true 122 | } 123 | 124 | task webpack(type: NodeTask, dependsOn: 'npmInstall') { 125 | def osName = System.getProperty("os.name").toLowerCase(); 126 | if (osName.contains("windows")) { 127 | script = project.file('node_modules/webpack/bin/webpack.js') 128 | } else { 129 | script = project.file('node_modules/.bin/webpack') 130 | } 131 | } 132 | 133 | processResources.dependsOn 'webpack' 134 | 135 | clean.delete << file('node_modules') 136 | 137 | ``` 138 | 139 | `./gradlew build` すると webpack が実行され、jar の中にビルド済みの js が梱包されます。 140 | 141 | # `npm run dev` コマンドの設定 142 | 143 | `webpack -w` を IntelliJ IDEA から呼び出しやすいように npm のサブコマンドを定義しておきます。 144 | package.json に以下のように記述します。 145 | 146 | ``` 147 | { 148 | "name": "spring-vue-sample", 149 | "version": "1.0.0", 150 | "description": "", 151 | "main": "index.js", 152 | "scripts": { 153 | "dev": "webpack -w" 154 | }, // 以下略 155 | } 156 | ``` 157 | 158 | こうすることにより、`npm run dev` で `webpack -w` を実行できます。 159 | 160 | # SEE ALSO 161 | 162 | * http://shigekitakeguchi.github.io/2016/08/10/1.html 163 | * https://webpack.js.org/plugins/extract-text-webpack-plugin/#usage-example-with-css 164 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.2.5.RELEASE' 3 | id 'io.spring.dependency-management' version '1.0.9.RELEASE' 4 | id 'java' 5 | id 'com.moowork.node' version '1.3.1' 6 | } 7 | 8 | group = 'com.example' 9 | version = '0.0.1-SNAPSHOT' 10 | 11 | description = """spring-vue-sample""" 12 | 13 | sourceCompatibility = 1.8 14 | targetCompatibility = 1.8 15 | tasks.withType(JavaCompile) { 16 | options.encoding = 'UTF-8' 17 | } 18 | 19 | configurations { 20 | compileOnly { 21 | extendsFrom annotationProcessor 22 | } 23 | } 24 | 25 | node { 26 | // version = '12.16.1' 27 | // npmVersion = '6.13.6' 28 | // download = true 29 | } 30 | 31 | repositories { 32 | mavenCentral() 33 | } 34 | 35 | dependencies { 36 | compile 'org.springframework.boot:spring-boot-starter-web' 37 | compile 'org.springframework.boot:spring-boot-starter-actuator' 38 | compile 'org.springframework.boot:spring-boot-starter-freemarker' 39 | // implementation 'org.springframework.session:spring-session-core' 40 | 41 | compileOnly 'org.projectlombok:lombok' 42 | annotationProcessor 'org.projectlombok:lombok' 43 | 44 | testCompile('org.springframework.boot:spring-boot-starter-test') { 45 | exclude(module: 'commons-logging') 46 | // exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' 47 | } 48 | } 49 | 50 | task webpack(type: NodeTask, dependsOn: 'npmInstall') { 51 | def osName = System.getProperty("os.name").toLowerCase(); 52 | if (osName.contains("windows")) { 53 | script = project.file('node_modules/webpack/bin/webpack.js') 54 | } else { 55 | script = project.file('node_modules/.bin/webpack') 56 | } 57 | } 58 | 59 | processResources.dependsOn 'webpack' 60 | 61 | clean.delete << file('node_modules') 62 | 63 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tokuhirom/spring-vue-sample/8ab6166c4d7978e858581ea520b7555545218384/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Mar 03 10:07:33 JST 2020 2 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.2.1-all.zip 3 | distributionBase=GRADLE_USER_HOME 4 | distributionPath=wrapper/dists 5 | zipStorePath=wrapper/dists 6 | zipStoreBase=GRADLE_USER_HOME 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 165 | if [[ "$(uname)" == "Darwin" ]] && [[ "$HOME" == "$PWD" ]]; then 166 | cd "$(dirname "$0")" 167 | fi 168 | 169 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 170 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /lombok.config: -------------------------------------------------------------------------------- 1 | config.stopBubbling = true 2 | lombok.addLombokGeneratedAnnotation = true 3 | lombok.anyConstructor.addConstructorProperties=true 4 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "spring-vue-sample", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "build": "webpack", 8 | "dev": "webpack -w" 9 | }, 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "axios": "^0.21.2", 14 | "bootstrap": "^4.4.1", 15 | "vue": "^2.6.11", 16 | "vue-router": "^3.1.6" 17 | }, 18 | "devDependencies": { 19 | "@babel/core": "^7.8.6", 20 | "@babel/preset-env": "^7.8.6", 21 | "babel-loader": "^8.0.6", 22 | "css-loader": "^3.4.2", 23 | "file-loader": "^5.1.0", 24 | "filemanager-webpack-plugin": "^2.0.5", 25 | "mini-css-extract-plugin": "^0.9.0", 26 | "style-loader": "^1.1.3", 27 | "url-loader": "^3.0.0", 28 | "vue-html-loader": "^1.2.4", 29 | "vue-loader": "^15.9.0", 30 | "vue-style-loader": "^4.1.2", 31 | "vue-template-compiler": "^2.6.11", 32 | "webpack": "^4.42.0", 33 | "webpack-cli": "^3.3.11", 34 | "webpack-notifier": "^1.8.0" 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'spring-vue-sample' 2 | -------------------------------------------------------------------------------- /src/main/java/com/example/SpringVueSampleApplication.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class SpringVueSampleApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(SpringVueSampleApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/example/controller/RootController.java: -------------------------------------------------------------------------------- 1 | package com.example.controller; 2 | 3 | import org.springframework.stereotype.Controller; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | 6 | @Controller 7 | public class RootController { 8 | @GetMapping("/") 9 | public String index() { 10 | return "index"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/example/controller/api/ProductsController.java: -------------------------------------------------------------------------------- 1 | package com.example.controller.api; 2 | 3 | import com.example.exception.NotFoundException; 4 | import com.example.model.Product; 5 | import com.example.repository.ProductRepository; 6 | import com.example.request.AddProductRequest; 7 | import com.example.request.EditProductRequest; 8 | import com.example.response.*; 9 | import org.springframework.validation.annotation.Validated; 10 | import org.springframework.web.bind.annotation.*; 11 | 12 | @RestController 13 | public class ProductsController { 14 | private final ProductRepository productRepository; 15 | 16 | public ProductsController(ProductRepository productRepository) { 17 | this.productRepository = productRepository; 18 | } 19 | 20 | @GetMapping("/api/product/") 21 | public ProductListResponse list() { 22 | return new ProductListResponse(productRepository.findAll()); 23 | } 24 | 25 | @GetMapping("/api/product/{id}") 26 | public ProductGetResponse get(@PathVariable("id") Integer id) { 27 | Product product = productRepository.get(id) 28 | .orElseThrow(() -> new NotFoundException("Unknown product ID: " + id)); 29 | return new ProductGetResponse(product); 30 | } 31 | 32 | @PutMapping("/api/product") 33 | public ProductCreateResponse create(@Validated @RequestBody AddProductRequest request) { 34 | Product product = productRepository.addProduct(request.getName()); 35 | return new ProductCreateResponse(product); 36 | } 37 | 38 | @PostMapping("/api/product/{id}") 39 | public ProductEditResponse edit(@PathVariable("id") Integer id, @Validated @RequestBody EditProductRequest request) { 40 | Product product = productRepository.edit( 41 | id, 42 | request.getName() 43 | ); 44 | return new ProductEditResponse(product); 45 | } 46 | 47 | @DeleteMapping("/api/product/{id}") 48 | public ProductDeleteResponse delete(@PathVariable("id") Integer id) { 49 | Product product = productRepository.delete(id); 50 | return new ProductDeleteResponse(product); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/example/exception/NotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.example.exception; 2 | 3 | public class NotFoundException extends RuntimeException { 4 | public NotFoundException(String message) { 5 | super(message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/example/model/Product.java: -------------------------------------------------------------------------------- 1 | package com.example.model; 2 | 3 | import lombok.Value; 4 | 5 | @Value 6 | public class Product { 7 | Integer id; 8 | String name; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/example/repository/ProductRepository.java: -------------------------------------------------------------------------------- 1 | package com.example.repository; 2 | 3 | import com.example.model.Product; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import java.util.Collection; 7 | import java.util.Map; 8 | import java.util.Optional; 9 | import java.util.concurrent.ConcurrentHashMap; 10 | import java.util.concurrent.atomic.AtomicInteger; 11 | 12 | @Repository 13 | public class ProductRepository { 14 | private final Map products; 15 | private final AtomicInteger idCounter; 16 | 17 | public ProductRepository() { 18 | idCounter = new AtomicInteger(0); 19 | products = new ConcurrentHashMap<>(); 20 | addProduct("foo"); 21 | addProduct("bar"); 22 | products.put(1, new Product(1, "foo")); 23 | products.put(2, new Product(2, "bar")); 24 | } 25 | 26 | public Collection findAll() { 27 | return this.products.values(); 28 | } 29 | 30 | public Product addProduct(String name) { 31 | Integer id = idCounter.incrementAndGet(); 32 | Product product = new Product( 33 | id, 34 | name 35 | ); 36 | this.products.put(id, product); 37 | return product; 38 | } 39 | 40 | public Product edit(Integer id, String name) { 41 | Product product = new Product(id, name); 42 | products.put(id, product); 43 | return product; 44 | } 45 | 46 | public Optional get(Integer id) { 47 | return Optional.ofNullable(this.products.get(id)); 48 | } 49 | 50 | public Product delete(Integer id) { 51 | return this.products.remove(id); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/example/request/AddProductRequest.java: -------------------------------------------------------------------------------- 1 | package com.example.request; 2 | 3 | import javax.validation.constraints.NotNull; 4 | 5 | import lombok.Value; 6 | 7 | @Value 8 | public class AddProductRequest { 9 | @NotNull 10 | String name; 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/example/request/EditProductRequest.java: -------------------------------------------------------------------------------- 1 | package com.example.request; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Value; 5 | 6 | import javax.validation.constraints.NotNull; 7 | 8 | import com.fasterxml.jackson.annotation.JsonCreator; 9 | 10 | @Value 11 | @AllArgsConstructor(onConstructor = @__({ @JsonCreator })) 12 | public class EditProductRequest { 13 | @NotNull 14 | String name; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/example/response/BasicResponse.java: -------------------------------------------------------------------------------- 1 | package com.example.response; 2 | 3 | import lombok.Value; 4 | 5 | @Value 6 | public class BasicResponse { 7 | String message; 8 | 9 | public BasicResponse() { 10 | this.message = null; 11 | } 12 | 13 | public BasicResponse(String message) { 14 | this.message = message; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/example/response/ProductCreateResponse.java: -------------------------------------------------------------------------------- 1 | package com.example.response; 2 | 3 | import com.example.model.Product; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import java.util.List; 9 | 10 | @Data 11 | @NoArgsConstructor 12 | @AllArgsConstructor 13 | public class ProductCreateResponse { 14 | Product products; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/example/response/ProductDeleteResponse.java: -------------------------------------------------------------------------------- 1 | package com.example.response; 2 | 3 | import com.example.model.Product; 4 | import lombok.Value; 5 | 6 | @Value 7 | public class ProductDeleteResponse { 8 | Product product; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/example/response/ProductEditResponse.java: -------------------------------------------------------------------------------- 1 | package com.example.response; 2 | 3 | import com.example.model.Product; 4 | import lombok.Value; 5 | 6 | @Value 7 | public class ProductEditResponse { 8 | Product product; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/example/response/ProductGetResponse.java: -------------------------------------------------------------------------------- 1 | package com.example.response; 2 | 3 | import com.example.model.Product; 4 | import lombok.Value; 5 | 6 | @Value 7 | public class ProductGetResponse { 8 | Product product; 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/example/response/ProductListResponse.java: -------------------------------------------------------------------------------- 1 | package com.example.response; 2 | 3 | import com.example.model.Product; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | import lombok.Value; 8 | 9 | import java.util.Collection; 10 | import java.util.List; 11 | 12 | @Value 13 | public class ProductListResponse { 14 | Collection products; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/js/app.js: -------------------------------------------------------------------------------- 1 | import Vue from "vue"; 2 | import App from './components/App.vue'; 3 | import VueRouter from 'vue-router'; 4 | import routes from './routes.js'; 5 | import axios from "axios"; 6 | 7 | Vue.use(VueRouter); 8 | 9 | axios.interceptors.response.use(null, function(error) { 10 | console.log(error); 11 | window.alert(error.config.url + ": " + error + "\n\n" + JSON.stringify(error.response.data)); 12 | return Promise.reject(error); 13 | }); 14 | 15 | const router = new VueRouter({ 16 | base: __dirname, 17 | routes: routes 18 | }); 19 | 20 | document.addEventListener("DOMContentLoaded", function () { 21 | new Vue({ 22 | router, 23 | render: h => h(App) 24 | }).$mount('#app'); 25 | }); 26 | -------------------------------------------------------------------------------- /src/main/js/components/App.vue: -------------------------------------------------------------------------------- 1 | 13 | 14 | 20 | -------------------------------------------------------------------------------- /src/main/js/pages/Home.vue: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/js/pages/NotFound.vue: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/main/js/pages/product/AddProduct.vue: -------------------------------------------------------------------------------- 1 | 10 | 11 | 30 | -------------------------------------------------------------------------------- /src/main/js/pages/product/DeleteProduct.vue: -------------------------------------------------------------------------------- 1 | 9 | 10 | 35 | -------------------------------------------------------------------------------- /src/main/js/pages/product/EditProduct.vue: -------------------------------------------------------------------------------- 1 | 10 | 11 | 36 | -------------------------------------------------------------------------------- /src/main/js/pages/product/ListProduct.vue: -------------------------------------------------------------------------------- 1 | 26 | 27 | 44 | 45 | -------------------------------------------------------------------------------- /src/main/js/routes.js: -------------------------------------------------------------------------------- 1 | import ListProduct from "./pages/product/ListProduct.vue"; 2 | import AddProduct from "./pages/product/AddProduct.vue"; 3 | import EditProduct from "./pages/product/EditProduct.vue"; 4 | import DeleteProduct from "./pages/product/DeleteProduct.vue"; 5 | import NotFound from "./pages/NotFound.vue"; 6 | import Home from "./pages/Home.vue"; 7 | 8 | export default [ 9 | { 10 | path: '/', 11 | component: Home 12 | }, 13 | { 14 | path: '/product/', 15 | component: ListProduct 16 | }, 17 | { 18 | path: '/product/add', 19 | component: AddProduct 20 | }, 21 | { 22 | path: '/product/edit/:id', 23 | component: EditProduct 24 | }, 25 | { 26 | path: '/product/delete/:id', 27 | component: DeleteProduct 28 | }, 29 | { 30 | path: '*', 31 | component: NotFound 32 | } 33 | ] 34 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | # Spring security enables Basic auth by default. 2 | # But in most cases, it's not needed. We should disable this. 3 | security: 4 | basic: 5 | enabled: false 6 | 7 | # When you can't serve generated resources from tomcat, you can enable following log for debugging. 8 | # logging.level.org.springframework.web.servlet.resource: trace 9 | -------------------------------------------------------------------------------- /src/main/resources/templates/index.ftlh: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | My page 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/test/java/com/example/SpringVueSampleApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.example; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class SpringVueSampleApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const webpack = require("webpack"); 2 | const MiniCssExtractPlugin = require('mini-css-extract-plugin'); 3 | const FileManagerPlugin = require('filemanager-webpack-plugin'); 4 | const VueLoaderPlugin = require('vue-loader/lib/plugin') 5 | 6 | module.exports = { 7 | mode: 'production', // https://webpack.js.org/configuration/mode/ 8 | entry: './src/main/js/app.js', 9 | output: { 10 | filename: 'js/bundle.js', 11 | path: __dirname + '/build/resources/main/static' 12 | }, 13 | module: { 14 | rules: [ 15 | { 16 | test: /\.vue$/, 17 | loader: 'vue-loader' 18 | }, 19 | { 20 | test: /\.js$/, 21 | use: { 22 | loader: 'babel-loader', 23 | options: { 24 | presets: ['@babel/preset-env'] 25 | } 26 | }, 27 | exclude: /node_modules/ 28 | }, 29 | { 30 | test: /\.css$/i, 31 | use: [{ 32 | loader: MiniCssExtractPlugin.loader, 33 | options: { 34 | publicPath: __dirname + "/build/resources/main/static/css/" 35 | } 36 | }, 'css-loader'], 37 | }, 38 | // bootstrap に含まれる font 等を data url に変換する。 39 | {test: /\.svg$/, use: [ {loader: 'url-loader', options: { mimetype: 'image/svg+xml' }} ]}, 40 | {test: /\.woff$/, use: [ {loader: 'url-loader', options: { mimetype: 'application/font-woff' }} ]}, 41 | {test: /\.woff2$/, use: [ {loader: 'url-loader', options: { mimetype: 'application/font-woff' }} ]}, 42 | {test: /\.eot$/, use: [ {loader: 'url-loader', options: { mimetype: 'application/font-woff' }} ]}, 43 | {test: /\.ttf$/, use: [ {loader: 'url-loader', options: { mimetype: 'application/font-woff' }} ]} 44 | ] 45 | }, 46 | plugins: [ 47 | new VueLoaderPlugin(), 48 | new MiniCssExtractPlugin({ 49 | filename: "/css/main.css" 50 | }), 51 | // IntelliJ IDEA uses out/production/resources/ as a classpath. 52 | new FileManagerPlugin({ 53 | onEnd: { 54 | copy: [ 55 | { 56 | source: __dirname + '/build/resources/main/static/js/bundle.js', 57 | destination: __dirname + '/out/production/resources/static/js/bundle.js' 58 | }, 59 | { 60 | source: __dirname + '/build/resources/main/static/css/main.css', 61 | destination: __dirname + '/out/production/resources/static/css/main.css' 62 | } 63 | ] 64 | } 65 | }) 66 | ] 67 | } 68 | ; 69 | 70 | --------------------------------------------------------------------------------