Spring boot入門篇

来源:https://www.cnblogs.com/zsliu/archive/2018/01/14/8284537.html
-Advertisement-
Play Games

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


1. Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Boot致力於在蓬勃發展的快速應用開發領域(rapid    application  development)成為領導者。
 可以 Maven | Gradle | Ant | Starters構建項目,參考:http://start.spring.io/ 可以選擇Maven或Gradle生成Demo,Spring boot微服務架構結合Docker容器運行。
  軟體版本運行要求請參考官網: Spring boot官網
  本實例軟體版本:JDK1.7 + Spring boot 1.3.5 + Spring 4.2.6 

  常用的starter以及用處可以列舉如下:

(1)spring-boot-starter: 這是核心Spring Boot starter,提供了大部分基礎功能,其他starter都依賴於它,因此沒有必要顯式定義它。

(2)spring-boot-starter-actuator:主要提供監控、管理和審查應用程式的功能。

(3)spring-boot-starter-jdbc:該starter提供對JDBC操作的支持,包括連接資料庫、操作資料庫,以及管理資料庫連接等等。

(4)spring-boot-starter-data-jpa:JPA starter提供使用Java Persistence API(例如Hibernate等)的依賴庫。

(5)spring-boot-starter-data-*:提供對MongoDB、Data-Rest或者Solr的支持。

(6)spring-boot-starter-security:提供所有Spring-security的依賴庫。

(7)spring-boot-starter-test:這個starter包括了spring-test依賴以及其他測試框架,例如JUnit和Mockito等等。

(8)spring-boot-starter-web:該starter包括web應用程式的依賴庫。

2.Maven構建項目pom代碼

  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3     <modelVersion>4.0.0</modelVersion>
  4 
  5     <groupId>ygnet</groupId>
  6     <artifactId>boot</artifactId>
  7     <version>0.0.1-SNAPSHOT</version>
  8     <packaging>jar</packaging>
  9 
 10     <name>Springboot</name>
 11     <url>http://maven.apache.org</url>
 12     
 13     <properties>
 14         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 15         <java.version>1.7</java.version>
 16     </properties>
 17     
 18     <!-- Spring Boot 啟動父依賴 -->
 19     <parent>
 20         <groupId>org.springframework.boot</groupId>
 21         <artifactId>spring-boot-starter-parent</artifactId>
 22         <version>1.3.5.RELEASE</version>
 23         <relativePath />
 24     </parent>
 25     <dependencies>
 26         <dependency>
 27             <groupId>junit</groupId>
 28             <artifactId>junit</artifactId>
 29             <version>4.12</version>
 30             <scope>test</scope>
 31         </dependency>
 32         <dependency>
 33           <groupId>org.springframework</groupId>
 34           <artifactId>spring-test</artifactId>
 35           <version>4.2.6.RELEASE</version>
 36         </dependency>
 37             
 38         <!-- Spring Boot web依賴 -->
 39         <dependency>
 40             <groupId>org.springframework.boot</groupId>
 41             <artifactId>spring-boot-starter-web</artifactId>
 42         </dependency>
 43         <dependency>
 44             <groupId>org.springframework.boot</groupId>
 45             <artifactId>spring-boot-starter</artifactId>
 46         </dependency>    
 47         <!--dependency>
 48             <groupId>org.springframework.boot</groupId>
 49             <artifactId>spring-boot-starter-test</artifactId>
 50             <scope>test</scope>
 51         </dependency-->
 52         <dependency>
 53             <groupId>org.springframework.boot</groupId>
 54             <artifactId>spring-boot-starter-jdbc</artifactId>
 55         </dependency>
 56         <dependency>
 57             <groupId>org.postgresql</groupId>
 58             <artifactId>postgresql</artifactId><scope>runtime</scope>
 59         </dependency>
 60         <dependency>
 61             <groupId>org.springframework.boot</groupId>
 62             <artifactId>spring-boot-starter-actuator</artifactId>
 63         </dependency>
 64     </dependencies>
 65     <build>
 66         <pluginManagement>  
 67             <plugins>  
 68               <plugin>  
 69                 <groupId>org.eclipse.m2e</groupId>  
 70                 <artifactId>lifecycle-mapping</artifactId>  
 71                 <version>1.0.0</version>  
 72                 <configuration>  
 73                   <lifecycleMappingMetadata>  
 74                     <pluginExecutions>  
 75                       <pluginExecution>  
 76                         <pluginExecutionFilter>  
 77                           <groupId>org.apache.maven.plugins</groupId>  
 78                           <artifactId>maven-dependency-plugin</artifactId>  
 79                           <versionRange>[2.0,)</versionRange>  
 80                           <goals>  
 81                             <goal>copy-dependencies</goal>  
 82                           </goals>  
 83                         </pluginExecutionFilter>  
 84                         <action>  
 85                           <ignore />  
 86                         </action>  
 87                       </pluginExecution>  
 88                     </pluginExecutions>  
 89                   </lifecycleMappingMetadata>  
 90                 </configuration>  
 91               </plugin>  
 92             </plugins>  
 93         </pluginManagement>
 94         <plugins>
 95             <!-- 打Jar包(META-INF) -->
 96             <plugin>
 97                 <groupId>org.apache.maven.plugins</groupId>  
 98                 <artifactId>maven-jar-plugin</artifactId>  
 99                 <configuration>  
100                     <archive>  
101                         <manifest>  
102                            <addClasspath>true</addClasspath>  
103                            <classpathPrefix>lib/</classpathPrefix>  
104                            <mainClass>yg.boot.App</mainClass>  
105                         </manifest>  
106                     </archive>  
107                 </configuration>  
108             </plugin>
109             <!-- 項目資源文件 -->
110             <plugin>  
111                 <groupId>org.apache.maven.plugins</groupId>  
112                 <artifactId>maven-resources-plugin</artifactId>  
113                 <version>2.5</version>  
114                 <executions>  
115                     <execution>  
116                         <phase>compile</phase>  
117                     </execution>  
118                 </executions>  
119                 <configuration>  
120                     <encoding>${project.build.sourceEncoding}</encoding>  
121                 </configuration>  
122             </plugin>
123             <!-- 是否啟動測試 -->
124             <plugin>
125                 <groupId>org.apache.maven.plugins</groupId>  
126                 <artifactId>maven-surefire-plugin</artifactId>
127                 <version>2.17</version> 
128                 <configuration>
129                   <skipTests>true</skipTests>  
130                 </configuration>
131             </plugin>
132             <!-- 複製依賴包到項目lib文件夾下 -->
133             <plugin>  
134                 <groupId>org.apache.maven.plugins</groupId>  
135                 <artifactId>maven-dependency-plugin</artifactId>  
136                 <version>2.8</version>  
137                 <executions>  
138                     <execution>  
139                         <phase>package</phase>  
140                         <goals>  
141                             <goal>copy-dependencies</goal>  
142                         </goals>  
143                     </execution>  
144                 </executions>
145                 <configuration>
146                     <outputDirectory>${project.basedir}/lib</outputDirectory>
147                     <includeScope>compile</includeScope>  
148                 </configuration>  
149             </plugin>
150             <!-- Spring boot 打包 -->
151             <plugin>
152                 <groupId>org.springframework.boot</groupId>
153                 <artifactId>spring-boot-maven-plugin</artifactId>
154             </plugin>
155         </plugins>
156     </build>
157 </project>

3.Controller

Spring Boot框架提供的機制便於工程師實現標準的RESTful介面,編寫Controller代碼,首先我們要在pom文件中添加對應的starter,即spring-boot-starter-web,對應的xml代碼示例為:
<dependency> 
<groupId>org.springframework.boot</groupId> 
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@RestController註解是@Controller和@ResponseBody的合集,表示這是個控制器bean,並且是將函數的返回值直接填入HTTP響應體中,是REST風格的控制器。
@RequestMapping("/test")表示該控制器處理所有“/test”的URL請求,具體由那個函數處理,要根據HTTP的方法來區分:GET表示查詢、POST表示提交、PUT表示更新、DELETE表示刪除。
Restful設計指南請參考:RESTFul
Controller的角色,大家可以看到,我這裡將很多業務代碼混淆在Controller的代碼中。實際上,根據程式員必知之前端演進史一文所述Controller層應該做的事是: 處理請求的參數 渲染和重定向 選擇Model和Service 處理Session和Cookies,我基本上認同這個觀點,最多再加上OAuth驗證(利用攔截器實現即可)。而真正的業務邏輯應該單獨分處一層來處理,即常見的service層;

 java代碼:

 1 package yg.boot.action;
 2 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
 3 import org.springframework.web.bind.annotation.RequestMapping;
 4 import org.springframework.web.bind.annotation.RestController;
 5 @RestController
 6 @EnableAutoConfiguration
 7 @RequestMapping("/test")
 8 public class AppController {    
 9     @RequestMapping("/sayhello")
10     public String sayHello(){
11         return "Hello World!";
12     }
13 }

4.Spring Boot啟動  

  @SpringBootApplication是這個註解是該應用程式入口的標誌,然後有熟悉的main函數,通過SpringApplication.run(xxxApplication.class, args)來運行Spring Boot應用。打開SpringBootApplication註解   可以發現,它是由其他幾個類組合而成的:@Configuration

(等同於 spring中的xml配置文件,使用Java文件做配置可以檢查類型安全)、@EnableAutoConfiguration(自動配置)、@ComponentScan(組件掃描,大家非常熟悉的,可以自動發現和裝配一些Bean)

   pom文件里可以看到,org.postgresql這個庫起作用的範圍是runtime,也就是說,當應用程式啟動時,如果Spring Boot在classpath下檢測到org.postgresql的存在,會自動配置postgresql資料庫連接。

Application.properties代碼:

 1 # DataSource settings
 2 spring.datasource.url=jdbc:postgresql://localhost:5432/jcbk
 3 spring.datasource.username=jcbk
 4 spring.datasource.password=123456
 5 spring.datasource.driver-class-name=org.postgresql.Driver
 6 
 7 # Tomcat Server settings (ServerProperties)
 8 server.port= 9080
 9 server.address= 127.0.0.1
10 server.sessionTimeout= 30
11 server.contextPath= /
12 
13 # Tomcat specifics
14 tomcat.accessLogEnabled= false
15 tomcat.protocolHeader= x-forwarded-proto
16 tomcat.remoteIpHeader= x-forwarded-for
17 tomcat.basedir=
18 tomcat.backgroundProcessorDelay=30 \# secs

java代碼:

 1 package yg.boot;
 2 import org.springframework.boot.SpringApplication;
 3 import org.springframework.boot.autoconfigure.SpringBootApplication;
 4 /**
 5  * Hello world!
 6  */
 7 @SpringBootApplication
 8 public class App {    
 9     public static void main(String[] args ){
10         SpringApplication.run(App.class,args);
11     }
12 }

直接運行App後,結果如下圖所示。啟動後訪問http://localhost:9080/test/sayhello, 輸出 Hello World!,如下所示:

5.項目打包

項目打包使用maven-jar-plugin插件即可,生成boot-0.0.1-SNAPSHOT.jar。spring-boot-maven-plugin插件將boot-0.0.1-SNAPSHOT.jar重命名為boot-0.0.1-SNAPSHOT.jar.original,然後生成新boot-0.0.1-SNAPSHOT.jar包,目錄結構為:
+---yg
          boot
+---org
          springframework
              boot
                 loader
+----lib
+----META-INF
+----application.properties

Meta-inf代碼:

 1 Manifest-Version: 1.0
 2 Implementation-Vendor: Pivotal Software, Inc.
 3 Implementation-Title: Springboot
 4 Implementation-Version: 0.0.1-SNAPSHOT
 5 Implementation-Vendor-Id: ygnet
 6 Built-By: oy
 7 Build-Jdk: 1.7.0_45
 8 Class-Path: lib/spring-test-4.2.6.RELEASE.jar lib/spring-core-4.2.6.RE
 9  LEASE.jar lib/spring-boot-starter-web-1.3.5.RELEASE.jar lib/spring-bo
10  ot-starter-tomcat-1.3.5.RELEASE.jar lib/tomcat-embed-core-8.0.33.jar 
11  lib/tomcat-embed-el-8.0.33.jar lib/tomcat-embed-logging-juli-8.0.33.j
12  ar lib/tomcat-embed-websocket-8.0.33.jar lib/spring-boot-starter-vali
13  dation-1.3.5.RELEASE.jar lib/hibernate-validator-5.2.4.Final.jar lib/
14  validation-api-1.1.0.Final.jar lib/jboss-logging-3.3.0.Final.jar lib/
15  classmate-1.1.0.jar lib/jackson-databind-2.6.6.jar lib/jackson-annota
16  tions-2.6.6.jar lib/jackson-core-2.6.6.jar lib/spring-web-4.2.6.RELEA
17  SE.jar lib/spring-aop-4.2.6.RELEASE.jar lib/aopalliance-1.0.jar lib/s
18  pring-beans-4.2.6.RELEASE.jar lib/spring-context-4.2.6.RELEASE.jar li
19  b/spring-webmvc-4.2.6.RELEASE.jar lib/spring-expression-4.2.6.RELEASE
20  .jar lib/spring-boot-starter-1.3.5.RELEASE.jar lib/spring-boot-1.3.5.
21  RELEASE.jar lib/spring-boot-autoconfigure-1.3.5.RELEASE.jar lib/sprin
22  g-boot-starter-logging-1.3.5.RELEASE.jar lib/logback-classic-1.1.7.ja
23  r lib/logback-core-1.1.7.jar lib/slf4j-api-1.7.21.jar lib/jcl-over-sl
24  f4j-1.7.21.jar lib/jul-to-slf4j-1.7.21.jar lib/log4j-over-slf4j-1.7.2
25  1.jar lib/snakeyaml-1.16.jar lib/spring-boot-starter-jdbc-1.3.5.RELEA
26  SE.jar lib/tomcat-jdbc-8.0.33.jar lib/tomcat-juli-8.0.33.jar lib/spri
27  ng-jdbc-4.2.6.RELEASE.jar lib/spring-tx-4.2.6.RELEASE.jar lib/postgre
28  sql-9.4.1208.jre7.jar lib/spring-boot-starter-actuator-1.3.5.RELEASE.
29  jar lib/spring-boot-actuator-1.3.5.RELEASE.jar
30 Start-Class: yg.boot.App
31 Created-By: Apache Maven 3.0.4
32 Spring-Boot-Version: 1.3.5.RELEASE
33 Main-Class: org.springframework.boot.loader.JarLauncher
34 Archiver-Version: Plexus Archiver

 

 Start-Class為Spring boot啟動類,Main-Class為main方法入口。

                                      END

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 100行代碼實現跳一跳輔助程式 寫在前面 好久沒寫博客了,今天來一發吧。分享一下今天下午用python寫的“跳一跳”小游戲的輔助程式。之前是準備用樹莓派操控一個“機械手指”來代替人的觸摸操作,但該方案還在醞釀中,實現了再分享。接下來要分享的是用“純軟體”的方法來玩“跳一跳”。 原理 原理其實很簡單, ...
  • 有很多學習C語言或者C++的朋友可能寫過貪吃蛇的作業,我也是其中之一。在最開始寫的時候自己水平很差,寫出的效果還不如許多同學從網上抄的。 這一系列博客都是使用C語言寫貪吃蛇,逐步提升難度,當然自己也好久不動手了,也算是自己複習一次C語言。 第一個貪吃蛇,因為許多剛學完C的同學並不瞭解太多東西,所以我 ...
  • 很多人喜歡逛油管看視頻,自然就會有一些喜歡的收藏集或者視頻作者,有時候想要下載下來保存在本地播放,這樣的話就不用每次FQ,畢竟有些代理的速度並不是很理想(如果你的代理速度炒雞快的話,請忽略這篇文章)。 當你想下載油管視頻,又覺得一些下載網站或者工具無法滿足你的要求的時候,比如我想定製下載的清晰度,我 ...
  • "如何處理 Python 入門難以進步的現象?" "Python 練習冊,每天一個小程式" " Python之美[從菜鳥到高手" " Python實戰" "Python 的練手項目有哪些值得推薦?" "廖雪峰實戰" "菜鳥教程實例(3.3)" "菜鳥教程100例(2.7)" PS :找的一些學習的東 ...
  • 一、重構簡單的CRUD 1.JDBC工具類 1.因為在crud中都包含一些相同的代碼所以可以提取出來,抽取代碼重構為工具類。 2.將工具類設置為static靜態類,方便調用,不需要new對象。 二、使用預編譯sql語句 1.預編譯sql語句的好處 1.效率高,預編譯對象把一些格式固定的SQL編譯後, ...
  • (一)指針數組 指針數組就是每一個元素存放一個地址,相當於一個指針變數。如:int *p[4]指針數組比較適合用來指向若幹字元串,使得處理字元串更加靈活。例如,現在要將若幹字元串按字母順序由小到大輸出 通過上例子,試比較if(strcmp(name[k],name[j])>0)和if(strcmp( ...
  • 上次通過eclipse在控制台輸出了hello world,是不是有點小激動啊,今天接著介紹Java基礎知識。 一、Java註釋 1、Java註釋語句不會被編譯器運行,不用擔心代碼因為許多註釋語句顯得臃腫而影響程式運行速度。 2、Java註釋有三種寫法。 一是雙斜杠 // 。需要註掉哪一行就添加到哪 ...
  • 1.python模塊:標準庫和第三方庫,第三方庫需要下載安裝2.模塊sys:命令 功能 sys.stdin 標準輸入流sys.stdout 標準輸出流sys.stderr 標準錯誤流 sys.argv[value] 接收命令行的參數。例如,windows下的命令行cmd裡面的參數。其中,argv[0 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...