SpringBoot入門-快速搭建web服務

一、介紹

Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Spring Boot致力於在蓬勃發展的快速應用開發領域(rapid application development)成爲領導者。

二、優點

如果我們要Spring寫一個HelloWorld,需要做什麼:
- 一個項目結構,通常使用Maven進行管理。
- 一個web.xml文件,其中聲明瞭Spring的DispatcherServlet。
- 一個啓用了Spring MVC的Spring配置。
- 一個控制器,響應HTTP請求(返回Hello World)。
- 一個用於部署應用程序的Web容器(Tomcat、Jetty等)
可以看到,和HelloWorld相關的只有控制器。

傳統的Spring搭建web服務,需要配置web.xml、加載spring、配置數據庫連接、配置日誌文件等等一系列操作。而Spring Boot則非常簡單,大大簡化了開發流程。

三、快速上手

1、配置項目依賴

國際慣例,先配置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相關的東西。

<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>

2、創建兩個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();
    }
}

3、創建Application

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

創建一個用來啓動SpringBoot的Application。

4、運行

直接運行APP中Main函數即可。
運行

之後打開瀏覽器訪問:http://127.0.0.1:8080/ 就可以看到controller的響應。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章