spring boot 入门

497 查看

spring boot致力于,帮助开发者快速构建spring应用。省略在繁琐的文件配置。

使用spring boot很容易创建相对独立,适用于生产环境的spring应用。

特性

  • 创建相对独立的spring 应用。

  • 嵌入tomcat,jetty,等应用服务器。而不需要生成war包。再部署到服务器。

  • 提供相对固定的基础配置已经配置模板,从而简化你的maven配置。

  • 方便的spring自动化配置。

  • 提供准生成环境的功能,如健康检测。

快速入门

使用maven,或者gradle可以非常方便的创建spring-boot入门应用。

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.2.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

hello/SampleController.java

package hello;

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

@Controller
@EnableAutoConfiguration
public class SampleController {

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

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

以上代码当中,@Controller、 @RequestMapping、@ResponseBody都是spring mvc中常见的注解。其中Controller注解用于标记,该类是一个controller,@ResponseBody用于标记该方法返回值直接作为处理结果返回给前端,而不需要去寻找试图。这两个注解可以使用@RestController代替。
@EnableAutoConfiguration这个注解告诉spring根据classpath引入的包,即根据依赖关系来进行自动配置。由于该工程是spring-boot-stater-web工程,默认添加了一些如tomcat,spring-web包等。因此spring会尝试以spring-web工程来配置工程。

详情建spirng-boot 官方docs stater guider