springboot学习第一步


关于springboot的介绍就不多说了,可以去百度。

默认的情况下,springboot1.4.0版本要求Java7以上和spring4.3.2以上,当然你也可以使用java1.6,只不过你需要额外的配置。

springboot是兼容maven3.2以上的,你可以现在你的pom.xml中定义一个spring-boot-starter-parent,这样它就会获得springboot的默认的属性,那么添加springboot的其它依赖,可不必指定它的version属性,springboot提供了一个maven的插件去打包成可执行的jar

<?xml version="1.0" encoding="UTF-8"?>

    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

    com.example
    myproject
    0.0.1-SNAPSHOT

    
    
        org.springframework.boot
        spring-boot-starter-parent
        1.4.0.RELEASE
    

    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
    

    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

关于gradle。springboot是兼容1.12版本以上的,下面是一个典型的build.gradle

buildscript {
    repositories {
        jcenter()
        maven { url "http://repo.spring.io/snapshot" }
        maven { url "http://repo.spring.io/milestone" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE")
    }
}

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

jar {
    baseName = 'myproject'
    version =  '0.0.1-SNAPSHOT'
}

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

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

一个简单的springboot的demo,用maven做依赖管理,添加spring-boot-starter-web依赖,你就可以获得一个简单web项目的所有相关依赖

<?xml version="1.0" encoding="UTF-8"?>

    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

    com.example
    myproject
    0.0.1-SNAPSHOT

    
    
        org.springframework.boot
        spring-boot-starter-parent
        1.4.0.RELEASE
    

    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
    

    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

建一个Example.java

import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

@RestController
@EnableAutoConfiguration
public class Example {

    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }

}

你可以直接在命令行中进入当前项目根目录,用mvn spring-boot:run可以启动项目,你也可以直接在eclipse中像普通java项目那样启动。当你在浏览器中输入localhost:8080,你就可以看到 Hello World!