25 -SpringBoot學習(1)- 入門案例

1 SpringBoot 介紹

Spring 框架對於很多 Java 開發人員來說都不陌生。自從 2002 年發佈以來,Spring 框架已經成爲企業應用開發領域非常流行的基礎框架。有大量的企業應用基於 Spring 框架來開發。Spring 框架包含幾十個不同的子項目,涵蓋應用開發的不同方面。如此多的子項目和組件,一方面方便了開發人員的使用,另外一個方面也帶來了使用方面的問題。每個子項目都有一定的學習曲線。開發人員需要了解這些子項目和組件的具體細節,才能知道如何把這些子項目整合起來形成一個完整的解決方案。在如何使用這些組件上,並沒有相關的最佳實踐提供指導。對於新接觸 Spring 框架的開發人員來說,並不知道如何更好的使用這些組件。Spring 框架的另外一個常見問題是要快速創建一個可以運行的應用比較麻煩。Spring Boot 是 Spring 框架的一個新的子項目,用於創建 Spring 4.0 項目。它的開發始於 2013 年。2014 年 4 月發佈 1.0.0 版本。它可以自動配置 Spring 的各種組件,並不依賴代碼生成和 XML 配置文件。Spring Boot 也提供了對於常見場景的推薦組件配置。Spring Boot 可以大大提升使用 Spring 框架時的開發效率

  • 使用Spring boot ,可以輕鬆的創建獨立運行的程序,非常容易構建獨立的服務組件,是實現分佈式架構、微服務架構利器。
  • Spring boot簡化了第三方包的引用,通過提供的starter,簡化了依賴包的配置

1.1 Spring boot的優點

  • 輕鬆創建獨立的Spring應用程序。
  • 內嵌Tomcat、jetty等web容器,不需要部署WAR文件。
  • 提供一系列的“starter” 來簡化的Maven配置,不需要添加很多依賴。
  • 開箱即用,儘可能自動配置Spring。

1.2 內置Servlet容器

在這裏插入圖片描述

2 入門案例

2.1 war 結構的項目

在這裏插入圖片描述
在這裏插入圖片描述

2.2 jar 包項目

在這裏插入圖片描述
在這裏插入圖片描述


  • pom.xml

  • spring-boot-starter-parent作用
    在pom.xml中引入spring-boot-start-parent,它可以提供dependency management,也就是說依賴管理,引入以後在申明其它dependency的時候就不需要version了,後面可以看到。

  • spring-boot-starter-web作用
    springweb 核心組件

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.tzb.springboot</groupId>
    <artifactId>springboot-jar</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>springboot-jar</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

  <!--springboot-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

  • 控制器
package com.tzb.springboot.web.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

// rest 風格的控制器
@RestController
@EnableAutoConfiguration // 自動配置,相當於寫了spring 配置文件
public class HelloController {

    @RequestMapping("hello")
    @ResponseBody // 返回的數據轉爲 json
    public String hello(){
        return "Hello World!";
    }

    public static void main(String[] args) {
        // 啓動 springboot 項目
        SpringApplication.run(HelloController.class);
    }
}

在這裏插入圖片描述


// rest 風格的控制器
@RestController
@EnableAutoConfiguration // 自動配置,相當於寫了spring 配置文件
public class HelloController {

    @RequestMapping("hello/{name}")
    @ResponseBody // 返回的數據轉爲 json
    public String hello(@PathVariable String name){
        return "Hello World! " + name;
    }

    public static void main(String[] args) {
        // 啓動 springboot 項目
        SpringApplication.run(HelloController.class);
    }
}

在這裏插入圖片描述

3 springboot 啓動方式

3.1 方式 1

在控制器配置EnableAutoConfiguration並使用SpringApplication啓動程序

3.2 方式 2 【常用】

創建一個App類,在App類中配置EnableAutoConfiguration和組件掃描ComponentScan,
然後使用SpringApplication啓動程序,這樣就可以訪問多個Controller了.


  • 控制器
package com.tzb.springboot.web.controller;

import com.tzb.springboot.model.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

// rest 風格的控制器
@RestController
@RequestMapping("user")
public class UserController {

    @RequestMapping("{id}")
    @ResponseBody // 返回的數據轉爲 json
    public User userInfo(@PathVariable Integer id){
        User user = new User("Mike", "123");
        user.setId(id);
        return user;
    }

  /*  public static void main(String[] args) {
        // 啓動 springboot 項目
        SpringApplication.run(UserController.class);
    }*/
}
  • App.java
package com.tzb.springboot;

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

@ComponentScan(basePackages = "com.tzb.springboot.web.controller")
@EnableAutoConfiguration
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

在這裏插入圖片描述

4 Spring Boot依賴介紹

  • spring-boot-starter 核心 POM,包含自動配置支持、日誌庫和對 YAML 配置文件的支持。
  • spring-boot-starter-amqp 通過 spring-rabbit 支持 AMQP
  • spring-boot-starter-aop 包含 spring-aop 和 AspectJ 來支持面向切面編程(AOP)。
  • spring-boot-starter-batch 支持 Spring Batch,包含 HSQLDB。
  • spring-boot-starter-data-jpa 包含 spring-data-jpa、spring-orm 和 Hibernate 來支持 JPA。
  • spring-boot-starter-data-mongodb 包含 spring-data-mongodb 來支持 MongoDB。
  • spring-boot-starter-data-rest 通過 spring-data-rest-webmvc 支持以 REST 方式暴露 Spring Data 倉庫。
  • spring-boot-starter-jdbc 支持使用 JDBC 訪問數據庫
  • spring-boot-starter-security 包含 spring-security。
  • spring-boot-starter-test 包含常用的測試所需的依賴,如 JUnit、Hamcrest、Mockito 和 spring-test 等。
  • spring-boot-starter-velocity 支持使用 Velocity 作爲模板引擎。
  • spring-boot-starter-web 支持 Web 應用開發,包含 Tomcat 和 spring-mvc。
  • spring-boot-starter-websocket 支持使用 Tomcat 開發 WebSocket 應用。
  • spring-boot-starter-ws 支持 Spring Web Services
  • spring-boot-starter-actuator 添加適用於生產環境的功能,如性能指標和監測等功能。
  • spring-boot-starter-remote-shell 添加遠程 SSH 支持
  • spring-boot-starter-jetty 使用 Jetty 而不是默認的 Tomcat 作爲應用服務器。
  • spring-boot-starter-log4j 添加 Log4j 的支持
  • spring-boot-starter-logging 使用 Spring Boot 默認的日誌框架 Logback
  • spring-boot-starter-tomcat 使用 Spring Boot 默認的 Tomcat 作爲應用服務器。

4.1 spring-boot-starter-web

  • POM 文件中可以看到,應用所聲明的依賴很少
  • 只有一個“org.springframework.boot:spring-boot-starter-web”
  • 而不是像其他 Spring 項目一樣需要聲明很多的依賴。
  • 當使用 Maven 命令“mvn dependency:tree”來查看項目實際的依賴時
  • 發現其中包含SpringMVC框架、SLF4J、Jackson、Hibernate Validator 和 Tomcat 等依賴。
  • 這實際上 Spring 推薦的 Web 應用中使用的開源庫的組合。

4.2 EnableAutoConfiguration

  • EnableAutoConfiguration”註解的作用在於讓 Spring Boot 根據應用所聲明的依賴來對 Spring 框架進行自動配置,這就減少了開發人員的工作量。
  • Spring Boot 推薦採用基於 Java 註解的配置方式,而不是傳統的 XML。只需要在主配置 Java 類上添加“@EnableAutoConfiguration”註解就可以啓用自動配置。
  • 註解“@RestController”和”@RequestMapping”由 Spring MVC 提供,用來創建 REST 服務。這兩個註解和 Spring Boot 本身並沒有關係。

5 web 開發

5.1 靜態資源的訪問

開發Web應用的時候,需要引用大量的js、css、圖片等靜態資源。
Spring Boot默認提供靜態資源目錄位置需置於classpath下,目錄名需符合如下規則:

  • /static
  • /public
  • /resources
  • /META-INF/resources

src/main/resources/目錄下創建static,在該位置放置一個圖片文件。啓動程序後,嘗試訪問http://localhost:8080/imgs/d.jpg。如能顯示圖片,配置成功。
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

5.2 全局捕獲異常

  • @ExceptionHandler 表示攔截異常

  • @ControllerAdvice

  • controller 的一個輔助類,最常用的就是作爲全局異常處理的切面類

  • 可以指定掃描範圍

  • 約定了幾種可行的返回值,如果是直接返回 model 類的話,需要使用

  • @ResponseBody進行 json 轉換


  • 異常類
package com.tzb.springboot.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
* 用於捕獲全局異常
* */
@ControllerAdvice // 控制器切面
public class GlobalExceptionHandler {
    // 處理異常的方法
    @ExceptionHandler(RuntimeException.class) // 捕獲運行時異常
    @ResponseBody // 返回 json
    public Map<String,Object> exceptionHandler(){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("errorCode", "101");
        map.put("errorMsg", "系統錯誤!");
        return map;
    }
}

在這裏插入圖片描述

  • 控制器
    在這裏插入圖片描述

  • App.java

@ComponentScan(basePackages = "com.tzb.springboot")
@EnableAutoConfiguration
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

在這裏插入圖片描述

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