nkimraの日記

技術的なメモのブログ。

IntelliJ + Spring Boot + GradleでHello Worldを表示

環境

MacOS 10.10.3 Yosemite
IntelliJ IDEA 14
Spring Boot 1.3
Gradle 2.3

Spring Bootの勉強のため、初めてIntelliJとGradleを使ってみた。

構成
f:id:nkimra:20150613080108j:plain

Projectの作成

1.Create New Projectを開く。
2.Gradleを選択し、次へ。
3.GroupI、ArtifactIdを設定する。
 GroupId:com.nkimra
 ArtifactId:springboot-sample
 Version 1.0-SNAPSHOT
4.以降の処理はすべて初期値でFinishまで進める。

Gradleの設定

build.gradleは、Spring Initializrを使って自動生成した。

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

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot' 

jar {
    baseName = 'springboot-sample'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

idea {
    module {
        inheritOutputDirs = false
        outputDir = file("$buildDir/classes/main/")
    }
}

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


dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    testCompile("org.springframework.boot:spring-boot-starter-test") 
}


eclipse {
    classpath {
         containers.remove('org.eclipse.jdt.launching.JRE_CONTAINER')
         containers 'org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8'
    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}

IntelliJの右側にあるGradleのRefreshボタンをクリックし、依存ライブラリをダウンロードする。
f:id:nkimra:20150612234351j:plain

InteliJの自動コンパイルを有効化にしておく。

⌘.でPreferencesを開く。
Build,Execution,Deployment → Compiler を開く。
Make project automaticallyにチェックを入れる。

実装

まずSpring Boot起動時に呼ばれるApplication.javaを作成する。

package com.nkimra;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

次にHello worldを出力するHelloControllerを作成する。

package com.nkimra.hello;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
public class HelloController {
    @RequestMapping("/")
    @ResponseBody
    public String index() {
        return "Hello world";
    }
}

ビルドと実行

GradleのTasksにあるらしい。
f:id:nkimra:20150613081003j:plain

まずビルドを試す。build→buildを実行し、「BUILD SUCCESSFUL」が出力されるのを確認。

8:06:05: Executing external task 'build'...
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:jar
:bootRepackage
:assemble
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE
:check UP-TO-DATE
:build

BUILD SUCCESSFUL

Total time: 11.636 secs
8:06:17: External task execution finished 'build'.

次にSpring Bootを実行してみる。
application→bootRunを実行する。

8:08:47: Executing external task 'bootRun'...
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:findMainClass
:bootRun

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v1.3.0.BUILD-SNAPSHOT)

2015-06-13 08:08:50.693  INFO 2473 --- [           main] com.nkimra.Application                   : Starting Application on Athena.local with PID 2473 (/Users/naoyuki/Copy/Dropbox/Dropbox/03_Dev/02_git/springboot-sample/build/classes/main started by naoyuki in /Users/naoyuki/Copy/Dropbox/Dropbox/03_Dev/02_git/springboot-sample)
2015-06-13 08:08:50.752  INFO 2473 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@cb0ed20: startup date [Sat Jun 13 08:08:50 JST 2015]; root of context hierarchy
2015-06-13 08:08:51.947  INFO 2473 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2015-06-13 08:08:53.015  INFO 2473 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2015-06-13 08:08:53.379  INFO 2473 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2015-06-13 08:08:53.383  INFO 2473 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.23
2015-06-13 08:08:53.527  INFO 2473 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2015-06-13 08:08:53.527  INFO 2473 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2779 ms
2015-06-13 08:08:54.395  INFO 2473 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2015-06-13 08:08:54.401  INFO 2473 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2015-06-13 08:08:54.402  INFO 2473 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2015-06-13 08:08:54.794  INFO 2473 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@cb0ed20: startup date [Sat Jun 13 08:08:50 JST 2015]; root of context hierarchy
2015-06-13 08:08:54.884  INFO 2473 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.nkimra.hello.HelloController.index()
2015-06-13 08:08:54.891  INFO 2473 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2015-06-13 08:08:54.891  INFO 2473 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2015-06-13 08:08:54.929  INFO 2473 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-06-13 08:08:54.929  INFO 2473 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-06-13 08:08:54.976  INFO 2473 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-06-13 08:08:55.132  INFO 2473 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2015-06-13 08:08:55.214  INFO 2473 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2015-06-13 08:08:55.217  INFO 2473 --- [           main] com.nkimra.Application                   : Started Application in 4.907 seconds (JVM running for 5.465)

ブラウザで「http://localhost:8080/」を開き、Hello worldが表示されることを確認する。