分布式--Spring Boot 微服務(wù)框架

1. Spring Boot

1). 簡介

Spring Boot 是由 Pivotal 團(tuán)隊(duì)提供的全新框架,其設(shè)計(jì)目的是用來簡化新 Spring 應(yīng)用的初始搭建以及開發(fā)過程。該框架使用了特定的方式來進(jìn)行配置,從而使開發(fā)人員不再需要定義樣板化的配置。

2). 好處

(1)它是Spring的升級版,Spring容器能做到的事情,它都能做到,而且更簡便,從配置形式上來說,SpringBoot完全拋棄了繁瑣的XML文件配置方式,而是替代性地用注解方式來實(shí)現(xiàn),雖然本質(zhì)來說,是差不多的(類似包掃描,注解掃描,類加載之類)。
(2)SpringBoot集成的插件更多,從而使用很多服務(wù),都只是引入一個(gè)依賴,幾個(gè)注解和Java類就可以用了,具體的參考相關(guān)手冊。
(3)在Web應(yīng)用開發(fā)這一塊,之前的應(yīng)用一般來說是打包成war包,再發(fā)布到相關(guān)服務(wù)器容器下(例如Tomcat),雖然SpringBoot也可以這么做,但在SpringBoot下更常見的形式是將SpringBoot應(yīng)用打包成可執(zhí)行jar包文件。之所以這么做,源于你可以直接將SpringBoot應(yīng)用看成是一個(gè)Java Application,其Web應(yīng)用可以沒有webapp目錄(更不用說web.xml了),它推薦使用html頁面,并將其作為靜態(tài)資源使用。

3). Spring Boot是什么

Spring Boot不是一個(gè)框架,它是一種用來輕松創(chuàng)建具有最小或零配置的獨(dú)立應(yīng)用程序的方式。這是方法用來開發(fā)基于Spring的應(yīng)用,但只需非常少的配置。它提供了默認(rèn)的代碼和注釋配置,快速啟動(dòng)新的Spring項(xiàng)目而不需要太多時(shí)間。它利用現(xiàn)有的Spring項(xiàng)目以及第三方項(xiàng)目來開發(fā)生產(chǎn)就緒(投入生產(chǎn))的應(yīng)用程序。它提供了一組pom或gradle構(gòu)建文件,可以使用它們添加所需的依賴項(xiàng),并且還便于自動(dòng)配置。
Spring Boot根據(jù)其類路徑上的庫自動(dòng)配置所需的類。假設(shè)應(yīng)用程序想要與數(shù)據(jù)庫交互,如果在類路徑上有Spring數(shù)據(jù)庫,那么它會自動(dòng)建立與數(shù)據(jù)源類的連接。


圖1.png
4). 主要目標(biāo)
  • 為所有Spring開發(fā)提供一個(gè)基本的,更快,更廣泛的入門體驗(yàn)。
  • 開箱即用,但隨著需求開始偏離默認(rèn)值,快速啟動(dòng)。
  • 提供大型項(xiàng)目(例如嵌入式服務(wù)器,安全性,度量,運(yùn)行狀況檢查,外部化配置)常見的一系列非功能特性。
  • 絕對沒有代碼生成以及不需要XML配置,完全避免XML配置。
  • 為了避免定義更多的注釋配置(它將一些現(xiàn)有的 Spring Framework 注釋組合成一個(gè)簡單的單一注釋)
  • 避免編寫大量import語句。
  • 提供一些默認(rèn)值,以便在短時(shí)間內(nèi)快速啟動(dòng)新項(xiàng)目。
5). 新項(xiàng)目使用Spring Boot
  • 簡化基于Java的應(yīng)用程序開發(fā),單元測試和集成測試過程。
  • 通過提供一些默認(rèn)值來減少開發(fā),單元測試和集成測試時(shí)間。
  • 提高生產(chǎn)力。
  • 當(dāng)使用默認(rèn)值時(shí),Spring Boot有自己的看法。如果不指定詳細(xì)信息,它將使用其自己的默認(rèn)配置。如果想要持久化,但是沒有在POM文件中指定任何東西,那么Spring Boot會- 將Hibernate帶有HSQLDB數(shù)據(jù)庫的配置作為JPA提供者。
  • 為大型項(xiàng)目(例如嵌入式服務(wù)器,安全性,度量,健康檢查,外部化配置)提供許多非常常見的非功能特性/解決方案。
6). 優(yōu)缺點(diǎn)

Spring Boot的優(yōu)點(diǎn):

  • 使用Java或Groovy開發(fā)基于Spring的應(yīng)用程序非常容易。
  • 它減少了大量的開發(fā)時(shí)間并提高了生產(chǎn)力。
  • 它避免了編寫大量的樣板代碼,注釋和XML配置。
  • Spring Boot應(yīng)用程序與其Spring生態(tài)系統(tǒng)(如Spring JDBC,Spring ORM,Spring Data,Spring Security等)集成非常容易。
  • 它遵循“自用默認(rèn)配置”方法,以減少開發(fā)工作量。
  • 它提供嵌入式HTTP服務(wù)器,如Tomcat,Jetty等,以開發(fā)和測試Web應(yīng)用程序非常容易。
  • 它提供CLI(命令行界面)工具從命令提示符,非常容易和快速地開發(fā)和測試Spring Boot(Java或Groovy)應(yīng)用程序。
  • 它提供了許多插件來開發(fā)和測試Spring啟動(dòng)應(yīng)用程序非常容易使用構(gòu)建工具,如Maven和Gradle。
  • 它提供了許多插件,以便與嵌入式和內(nèi)存數(shù)據(jù)庫工作非常容易。

Spring Boot的限制:

  • 將現(xiàn)有或傳統(tǒng)的Spring Framework項(xiàng)目轉(zhuǎn)換為Spring Boot應(yīng)用程序是一個(gè)非常困難和耗時(shí)的過程。它僅適用于全新Spring項(xiàng)目。

2. Spring Boot

1). 入門

Spring Boot項(xiàng)目歸根只是一個(gè)常規(guī)的Spring項(xiàng)目,只是利用了Spring Boot啟動(dòng)程序和自動(dòng)配置。要?jiǎng)?chuàng)建Spring Boot應(yīng)用程序的方法,Spring團(tuán)隊(duì)(The Pivotal Team)提供了以下三種方法。

可以使用Spring Boot開發(fā)兩種基于Spring的應(yīng)用程序:

  • 基于Java的應(yīng)用程序
  • 基于Groovy的應(yīng)用程序
圖2.png
2). Spring Boot CLI

I. 下載并解壓

圖3.png

在Windows系統(tǒng)中命令提示符中設(shè)置Spring Boot CLI環(huán)境變量:
右鍵“我的電腦”->”高級系統(tǒng)設(shè)置”->”高級”->”環(huán)境變量”->選擇”PATH”并新建并加上面的路徑D:\distribution\spring-2.0.2.RELEASE\bin;
圖4.png

驗(yàn)證:

spring --version
圖5.png

II. spring 命令語法查看spring --help

圖6.png

III. 創(chuàng)建HelloWorld.groovy文件

@RestController
class HelloWorld {
    @RequestMapping("/")
    String hello() {
        "Hello mazaiting."
    }
}
圖6.png

IV. 運(yùn)行

spring run HelloWorld.groovy
圖7.png

V. 測試
在瀏覽器輸入http://localhost:8080/即可訪問

圖8.png

3). Maven 安裝Spring Boot
    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
    </parent>

    <!-- Add typical dependencies for a web application -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
4). Eclipse 使用 Spring Boot

I. 在pom.xml文件中添加SpringBoot的依賴

<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.mazaiting</groupId>
    <artifactId>SpringBootTest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringBootTest</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <!-- Spring-Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Spring-Boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>

II. 創(chuàng)建HelloWorld類

@RestController
@EnableAutoConfiguration
public class HelloWorld {

    @RequestMapping("/")
    String home() {
        return "Hello mazaiting";
    }
    
    public static void main(String[] args) {
        SpringApplication.run(HelloWorld.class, args);
    }
}

III. 執(zhí)行結(jié)果

圖9.png

在瀏覽器輸入http://localhost:8080/
圖10.png

IV. 注解解釋

  • @RestController: 構(gòu)造型注釋, 指定控制器,Spring會在處理傳入的Web請求時(shí)考慮它.
  • @RequestMapping:注解提供了“路由”信息。它告訴Spring任何帶有路徑“/”的HTTP請求應(yīng)該映射到home方法。[@RestController](https://github.com/RestController "@RestController")注解告訴Spring將生成的字符串直接返回給調(diào)用者。
  • @EnableAutoConfiguration: 允許自動(dòng)配置

V. 創(chuàng)建可執(zhí)行的jar包

  • 在pom.xml的project節(jié)點(diǎn)下添加
    <build>
        <plugins>
            <!-- 用于創(chuàng)建可執(zhí)行jar -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  • 在項(xiàng)目的根目錄下執(zhí)行dos命令mvn package
    圖11.png

    圖12.png
  • 執(zhí)行完成后\SpringBootTest\target\目錄下生成SpringBootTest-0.0.1-SNAPSHOT.jar文件
    圖13.png
  • 執(zhí)行java -jar target/SpringBootTest-0.0.1-SNAPSHOT.jar命令運(yùn)行,并在瀏覽器輸入http://localhost:8080/,同樣可看到執(zhí)行效果.
5). Spring Boot JSP 實(shí)例

I. 創(chuàng)建Maven Web項(xiàng)目


圖14.png

II. 在pom文件中添加依賴

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mazaiting</groupId>
    <artifactId>SpringBoot-JSP</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBoot-JSP Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <!-- Spring-Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
    </parent>
    <!-- 配置Java版本 -->
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- Spring-Boot: This is a web application  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Tomcat embedded container-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- Need this to compile JSP -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
         <!-- JSTL for JSP -->
        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>       
        <!-- https://mvnrepository.com/artifact/taglibs/standard -->
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <!-- Optional, test for static content, bootstrap CSS-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>SpringBoot-JSP</finalName>
        <plugins>
            <!-- Package as an executable jar/war -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

實(shí)現(xiàn)依賴關(guān)系:mvn dependency:tree

圖15.png

III. SpringBootServletInitializer執(zhí)行傳統(tǒng)的WAR部署運(yùn)行SpringApplication

// 注解為SpringBoot應(yīng)用
@SpringBootApplication
public class SpringBootWebApplication extends SpringBootServletInitializer{
    
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(SpringBootWebApplication.class);
    }
    
    public static void main(String[] args) {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }
    
}

IV. 創(chuàng)建控制器

@Controller
public class WelcomeController {
    
    // 注入應(yīng)用配置 application.properties
    @Value("${welcome.message}")
    private String message = "Hello World";
    
    @RequestMapping("/")
    public String welcome(Map<String, Object> model) {
        model.put("message", this.message);
        return "welcome";
    }
}

V. welcome.jsp頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <!-- 鏈接bootstrap -->
        <!-- 
            href中的內(nèi)容寫為:webjars/bootstrap/3.3.7/css/bootstrap.css
            加載地址為:http://localhost:8080/SpringBoot-JSP/webjars/bootstrap/3.3.7/css/bootstrap.css
            href中的內(nèi)容寫為:/webjars/bootstrap/3.3.7/css/bootstrap.css
            加載地址為:http://localhost:8080/webjars/bootstrap/3.3.7/css/bootstrap.css
            使用中建議寫為webjars/bootstrap/3.3.7/css/bootstrap.css
        -->
        <link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.css"/>
        <%-- <spring:url value="/css/main.css" var="springCss"/>
        <link href="${springCss}" rel="stylesheet"/> --%>
        <script type="text/javascript" src="webjars/jquery/1.11.1/jquery.min.js"></script>
        <c:url value="/css/main.css" var="jstlCss"></c:url>
        <link href="${jstlCss }" rel="stylesheet"/>
        <title>SpringBootTest</title>
    </head>
    <body> 
        <nav class="navbar navbar-inverse">
            <div class="container">
                <div class="navbar-header">
                    <a class="navbar-brand" href="#">Spring Boot</a>
                </div>
            </div>
            <div id="navbar" class="collapse navbar-collapse">
                <ul class="nav nav-bar-nav">
                    <li class="active"><a href="#">Home</a></li>
                    <li><a href="#about">About</a></li>
                </ul>
            </div>
        </nav>
        <div class="container">
            <div class="starter-template">
                <h1>Spring Boot Web JSP Example</h1>
                <h2>Message: ${message }</h2>
            </div>
        </div>
        <script type="text/javascript" src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </body>
</html>

href中的內(nèi)容寫為:webjars/bootstrap/3.3.7/css/bootstrap.css
加載地址為:http://localhost:8080/SpringBoot-JSP/webjars/bootstrap/3.3.7/css/bootstrap.css

href中的內(nèi)容寫為:/webjars/bootstrap/3.3.7/css/bootstrap.css
加載地址為:http://localhost:8080/webjars/bootstrap/3.3.7/css/bootstrap.css

使用中建議寫為webjars/bootstrap/3.3.7/css/bootstrap.css

main.css

h1 {
    color: #00F;
}
h2 {
    color: #F00;
}

VI. 在/src/main/resources/目錄下創(chuàng)建application.properties及application-dev.properties、application-prod.properties、application-test.properties。

  • application-dev.properties:用于開發(fā)環(huán)境
  • application-test.properties:用于測試環(huán)境
  • application-prod.properties:用于生產(chǎn)環(huán)境

在application.properties文件中配置使用哪一類型的配置文件, prefix和suffix配置視圖層的前后綴。

spring.mvc.view.prefix: /jsp/
spring.mvc.view.suffix: .jsp
spring.profiles.active= dev

application-dev.properties

welcome.message: Hello mazaiting1

application-test.properties

welcome.message: Hello mazaiting2

application-prod.properties

welcome.message: Hello mazaiting3

VII. 代碼結(jié)構(gòu)


圖16.png

VIII. 運(yùn)行測試一:在SpringBootWebApplication類上右鍵Run As -> Java Application, 在瀏覽器中輸入http://localhost:8080/

圖17.png

IX.. 運(yùn)行測試二:在項(xiàng)目的根目錄下,在命令提示符輸入mvn spring-boot:run,然后在瀏覽器輸入http://localhost:8080/也可呈現(xiàn)效果

圖18.png

X. 運(yùn)行測試三:在工程右鍵-> Run As -> Run on Server部署在Tomcat容器中, 然后再瀏覽器中輸入http://localhost:8080/SpringBoot-JSP/即可訪問

圖19.png

XI. JSP限制
不能創(chuàng)建可執(zhí)行jar來運(yùn)行這個(gè)嵌入式Tomcat + JSP Web示例,因?yàn)門omcat中有一個(gè)硬編碼文件模式。

6). Spring Boot創(chuàng)建war包,并部署在Tomcat

I. 使用命令提示符進(jìn)入項(xiàng)目根目錄

mvn clean package
圖20.png

II. 執(zhí)行成功后,項(xiàng)目的\SpringBoot-JSP\target\目錄下出現(xiàn)SpringBoot-JSP.war

圖21.png

7). Spring Boot + Thymeleaf 模板引擎 -- 可執(zhí)行JAR文件

I. 引入依賴

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mazaiting</groupId>
    <artifactId>SpringBoot-Thymeleaf</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBoot-Thymeleaf Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
    </parent>
    <!-- Java版本 -->
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- hot swapping, disable cache for template, enable live reload -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- Optional, for bootstrap -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>SpringBoot-Thymeleaf</finalName>
        <plugins>
            <!-- Package as an executable jar/war -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

spring-boot-devtools有助于禁用緩存并啟用熱插拔,以便開發(fā)人員總是看到最后的更改。嘗試修改Thymeleaf模板或?qū)傩晕募⑿聻g覽器以查看更改立即生效。
II. 創(chuàng)建SpringBootWebApplication

@SpringBootApplication
public class SpringBootWebApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }
}

III. 創(chuàng)建WelcomeController

@Controller
public class WelcomeController {
    @Value("${welcome.message}")
    private String message= "Hello World";
    
    @RequestMapping("/")
    public String welcome(Map<String, Object> model){
        model.put("message", this.message);
        return "welcome";
    }
}

IV. Thymeleaf +資源+靜態(tài)文件

  • welcome.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>Spring Boot Thymeleaf Hello World 示例</title>
        <link rel="stylesheet" type="text/css" href="webjars/bootstrap/3.3.7/css/bootstrap.css"/>
        <link rel="stylesheet" th:href="@{/css/main.css}" href="../../css/main.css"/>
        <script type="text/javascript" src="webjars/jquery/1.11.1/jquery.min.js"></script>
    </head>
    <body>
        <nav class="navbar navbar-inverse">
            <div class="container">
                <div class="navbar-header">
                    <a class="navbar-brand" href="#">Spring Boot</a>
                </div>
                <div id="navbar" class="collapse navbar-collapse">
                    <ul class="nav navbar-nav">
                        <li class="avtive"><a href="#">首頁</a></li>
                        <li><a href="#about">關(guān)于</a></li>
                    </ul>
                </div>
            </div>
        </nav>
        <div class="container">
            <div class="starter-template">
                <h1>Spring Boot Web Thymeleaf 示例</h1>
                <h2>
                    <span th:text="'Message: ' + ${message}"></span>
                </h2>
            </div>
        </div>
        <script type="text/javascript" src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </body>
</html>
  • main.css
h1 {
    font-size: 20pt;
}
h2 {
    font-size: 16pt;
}
  • application.properties
welcome.message: Hello, mazaiting
  • 目錄結(jié)構(gòu)


    圖22.png

V. 運(yùn)行方式一:運(yùn)行SpringBootWebApplication,瀏覽器輸入http://localhost:8080/

圖23.png

VI. 運(yùn)行方式二:在命令提示符的項(xiàng)目根目錄下執(zhí)行mvn spring-boot:run,瀏覽器輸入http://localhost:8080/即可顯示效果
VII. 運(yùn)行方式三:在命令提示符的項(xiàng)目根目錄下執(zhí)行mvn clean package,創(chuàng)建可執(zhí)行jar包,運(yùn)行jar包,瀏覽器輸入http://localhost:8080/即可顯示效果。想要生成jar包,在pom.xml文件中,一定有此行<packaging>war</packaging>

8). Spring Boot 非Web應(yīng)用--命令行應(yīng)用

I. 創(chuàng)建Maven的普通Java工程,并在pom.xml文件中添加依賴

<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.mazaiting</groupId>
    <artifactId>SpringBoot-Console</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringBoot-Console</name>
    <url>http://maven.apache.org</url>
    <!-- Spring-Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Package as an executable jar/war -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

II. 創(chuàng)建HelloService服務(wù)

@Service
public class HelloMessageService {
    
    @Value("${name}")
    private String name;

    public String getMessage() {
        return getMessage(name);
    }
    
    public String getMessage(String name) {
        return "Hello " + name;
    }
    
}

III. application.properties內(nèi)容

name=mazaiting

IV. SpringBootConsoleApplication應(yīng)用

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner{

    @Autowired
    private HelloMessageService helloService;
    
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(SpringBootConsoleApplication.class);
        application.setBannerMode(Banner.Mode.OFF);
        application.run(args);
    }
    
    @Override
    public void run(String... args) throws Exception {
        if (args.length > 0) {
            System.out.println(helloService.getMessage(args[0].toString()));
        } else {
            System.out.println(helloService.getMessage());
        }
    }

}

V. 目錄結(jié)構(gòu)


圖24.png

VI. 運(yùn)行

  • 生成jar包
mvn package
  • 運(yùn)行1
java -jar target/SpringBoot-Console-0.0.1-SNAPSHOT.jar

結(jié)果:Hello mazaiting

  • 運(yùn)行2
java -jar target/SpringBoot-Console-0.0.1-SNAPSHOT.jar spring-boot

結(jié)果:Hello spring-boot

9). Spring Boot 屬性配置

I. pom.xml文件

<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.mazaiting</groupId>
    <artifactId>SpringBoot-Config</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringBoot-Config</name>
    <url>http://maven.apache.org</url>
    <!-- Spring-Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- Spring-Boot: This is a web application  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Package as an executable jar/war -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

II. @Value使用

@Component
@PropertySource("classpath:global.properties")
public class GlobalProperties {

    @Value("${thread-pool}")
    private int threadPool;

    @Value("${email}")
    private String email;

    //getters and setters

}

III. ConfigurationProperties

@Component
@PropertySource("classpath:global.properties")
@ConfigurationProperties
public class GlobalProperties {

    private int threadPool;
    private String email;

    //getters and setters

}

IV. 配置文件
global.properties文件

email=zaitingma@foxmail.com
thread-pool=12

application.properties文件

#Logging
logging.level.org.springframework.web=ERROR
logging.level.com.mazaiting=DEBUG

#Global 
email=1425941077@qq.com
thread-pool=10

#App
app.menus[0].title=Home
app.menus[0].name=Home
app.menus[0].path=/
app.menus[1].title=Login
app.menus[1].name=Login
app.menus[1].path=/login

app.compiler.timeout=5
app.compiler.output-folder=/temp/

app.error=/error/

注: 如果在application.properties文件中有與global.properties中有相同的屬性,取值時(shí)則取application.properties中的配置
V. 對應(yīng)的java文件
AppProperties.java

@Component
//prefix app, find app.* values
@ConfigurationProperties("app") 
public class AppProperties {
    private String error;
    private List<Menu> menus = new ArrayList<>();
    private Compiler compiler = new Compiler();
    
    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public List<Menu> getMenus() {
        return menus;
    }

    public void setMenus(List<Menu> menus) {
        this.menus = menus;
    }

    public Compiler getCompiler() {
        return compiler;
    }

    public void setCompiler(Compiler compiler) {
        this.compiler = compiler;
    }

    public static class Menu {
        private String name;
        private String path;
        private String title;
        
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        @Override
        public String toString() {
            return "Menu [name=" + name + ", path=" + path + ", title=" + title + "]";
        }
    }
    
    public static class Compiler {
        private String timeout;
        private String outputFolder;
        public String getTimeout() {
            return timeout;
        }
        public void setTimeout(String timeout) {
            this.timeout = timeout;
        }
        public String getOutputFolder() {
            return outputFolder;
        }
        public void setOutputFolder(String outputFolder) {
            this.outputFolder = outputFolder;
        }
        @Override
        public String toString() {
            return "Compiler [timeout=" + timeout + ", outputFolder=" + outputFolder + "]";
        }
    }

    @Override
    public String toString() {
        return "AppProperties [error=" + error + ", menus=" + menus + ", compiler=" + compiler + "]";
    }
}

GlobalProperties.java

@Component
@PropertySource("classpath:global.properties")
public class GlobalProperties {
    @Value("${thread-pool}")
    private int threadPool;
    @Value("${email}")
    private String email;
    public int getThreadPool() {
        return threadPool;
    }
    public void setThreadPool(int threadPool) {
        this.threadPool = threadPool;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "GlobalProperties [threadPool=" + threadPool + ", email=" + email + "]";
    }
}

VI. 應(yīng)用入口SpringBootWebApplication

@SpringBootApplication
public class SpringBootWebApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }
}

VII. 控制器

@Controller
public class WelcomeController {
    private static final Logger LOGGER = LoggerFactory.getLogger(WelcomeController.class);
    private GlobalProperties global;
    private AppProperties app;
    
    @Autowired
    public void setApp(AppProperties app) {
        this.app = app;
    }
    
    @Autowired
    public void setGlobalProperties(GlobalProperties global) {
        this.global = global;
    }
    
    @RequestMapping("/")
    public String welcome(Map<String, Object> model) {
        String globalProperties = global.toString();
        String appProperties = app.toString();
        
        LOGGER.debug("Welcome {}, {}", app, global);
        
        model.put("message", appProperties + globalProperties);
        return "welcome";
    }
    
}

VIII. 運(yùn)行SpringBootWebApplication,瀏覽器輸入http://localhost:8080/,查看控制臺

2018-05-14 13:07:22.056 DEBUG 4228 --- [nio-8080-exec-3] com.mazaiting.config.WelcomeController   : 
Welcome AppProperties [error=/error/, menus=[Menu [name=Home, path=/, title=Home], 
Menu [name=Login, path=/login, title=Login]], compiler=Compiler [timeout=5, outputFolder=/temp/]],
 GlobalProperties [threadPool=10, email=1425941077@qq.com]

IX. 驗(yàn)證

@Component
@ConfigurationProperties
public class GlobalProperties {

    @Max(5)
    @Min(0)
    private int threadPool;

    @NotEmpty
    private String email;

    //getters and setters
}
10). 配置文件中配置logging
#Logging
# log level 日志等級
logging.level.org.springframework.web=ERROR
logging.level.com.mazaiting=DEBUG
# log file 日志文件存放路徑
#logging.file=${java.io.tmpdir}/application.log
# output to a file 存放路徑
logging.file=C:/Users/Administrator/Desktop/mylog.log
# pattern 格式化文件內(nèi)容
logging.pattern.file="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n"

代碼下載

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容