takayuki_tk's diary

本当はScalaとかHaskellを使いたい

awesome! Spring-Boot

Spring-Bootがすごいので宣伝です。

僕はXML地獄といわれた頃からSpringをつかっています。

Spring1.x + Struts1.x + ibatis、、とかいう構成。

何かあってもXMLを変更するだけです! コードを修正する必要はありません!

なんて言葉が(確か)は流行っていた。 そりゃあれだけXML書けばXMLで何でもできるでしょ、ってくらいXMLばかりでした。

それに比べれば最近のSpring3.xはだいぶ楽ですが、それでも0から作るのは結構しんどいです。

おそらくほとんどの人が前回作った設定ファイルをコピーしているのではないでしょうか? (少なくとも僕はコピーしてます。。)

Spring-Bootを使えばHello Worldを0から5分でできました。

http://spring.io/guides/gs/spring-boot/#scratch

ここからは上ブログからの抜粋なので英語読める方は上を見てください。
忙しい人はこれだけやれば動きます。

  1. ディレクトリの作成 $mkdir -p src/main/java/hello

2.build.graldeの作成 プロジェクトのルートに作成します。

buildscript {
    repositories {
        maven { url "http://repo.spring.io/libs-snapshot" }
        mavenLocal()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:0.5.0.M4")
    }
}

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

jar {
    baseName = 'gs-spring-boot'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
    maven { url "http://repo.spring.io/libs-snapshot" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web:0.5.0.M4") {
        exclude module: "spring-boot-starter-tomcat"
    }
    compile("org.springframework.boot:spring-boot-starter-jetty:0.5.0.M4")
    testCompile("junit:junit:4.11")
}

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

3.controllerの作成 src/main/java/hello/HelloController.java

package hello;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
public class HelloController {

    @RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }

}

4.applicationファイルの作成 src/main/java/hello/Application.java

package hello;

import java.util.Arrays;

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

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);

        System.out.println("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    }

}

あとは

gradle wrapper
./gradlew build && java -jar build/libs/gs-spring-boot-0.1.0.jar

これで http://localhost:8080/ にアクセスできます。

、、、まあここからDBの設定したり、viewの設定したりと茨の道が待ってそうですが。。 きっとその辺もそのうちなんとかなると信じています。