SpringBoot入门-快速搭建web服务

1、介绍

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员再也不须要定义样板化的配置。经过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。java

2、优势

若是咱们要Spring写一个HelloWorld,须要作什么:
- 一个项目结构,一般使用Maven进行管理。
- 一个web.xml文件,其中声明了Spring的DispatcherServlet。
- 一个启用了Spring MVC的Spring配置。
- 一个控制器,响应HTTP请求(返回Hello World)。
- 一个用于部署应用程序的Web容器(Tomcat、Jetty等)
能够看到,和HelloWorld相关的只有控制器。web

传统的Spring搭建web服务,须要配置web.xml、加载spring、配置数据库链接、配置日志文件等等一系列操做。而Spring Boot则很是简单,大大简化了开发流程。spring

3、快速上手

一、配置项目依赖

国际惯例,先配置springBoot相关的maven依赖数据库

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

这里配置了SpringBoot的parent,若是项目自己有parent的话,则能够修改成下面这样,或者在你的parent中配置SpringBoot相关的东西。api

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

  <!--ImportdependencymanagementfromSpringBoot-->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>1.5.8.RELEASE</version>
    <type>pom</type>
    <scope>import</scope>
  </dependency>
</dependencies>

二、建立两个controller

相似下面的建立controller,主要是写一些业务逻辑在里面。浏览器

@RestController
@EnableAutoConfiguration
public class SayHelloController {

    @RequestMapping("/")
    String index() {
        return "hello world!";
    }
}
@Controller
@RequestMapping("now")
public class TimeController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    @ResponseBody
    String user() {
        return new Date().toString();
    }
}

三、建立Application

@ComponentScan(value = {"com.demo.controller"})
@EnableAutoConfiguration
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class);
    }
}

建立一个用来启动SpringBoot的Application。app

四、运行

直接运行APP中Main函数便可。
运行框架

以后打开浏览器访问:http://127.0.0.1:8080/ 就能够看到controller的响应。maven