一、快速構建Springboot應用
1、基本概念
Spring的出現對於企業級應用來說是一個福音,它讓企業級應用開發更加地簡單。但是隨著Spring的不斷發展,它也慢慢變得越來越重。即使apache出品的maven工具能夠使得項目創建、管理更加地輕便,但對於開發人員來說依舊存在負擔:
1)不得不處理xml等配置文件;
2)不得補處理各種依賴包;
而Spring的作者們也意識到了這一點,於是Springboot出現了。
Springboot出現的意義就在於快速創建並運行一個應用程序,如果之前我們需要十分鐘去創建一個簡單的spring項目,那麽現在我們只需要十幾秒鐘就能創建一個springboot的應用程序。
2、環境
本文編寫的時候,springboot的穩定版本是:2.0.1;
它需要:
1)JDK1.8+;
2)maven3.2+或gradle4+;
3) spring framework 5.0.5.release;
開發工具使用:
1)intellij IDEA;
2) Spring tool suite(STS);
3、構建Spring應用
1)打開IDEA開發工具,默認帶了STS套件;
2)new -> project -> Spring Initializer -> next -> 填寫項目信息 -> 勾選web -> 填寫項目名稱和路徑 -> finish
當maven處理完畢,一個簡單的Springboot項目就已經構建好了。
4、測試
我們在類路徑下編寫一個controller
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SampleController { @RequestMapping(value = "hello") public String hello(){ return "Hello World"; } }
運行main方法啟動程序
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }
控制臺上看到,我們在8080端口下tomcat運行成功了(備註:springboot2.0.1內置了tomcat8.5,servlet版本是3.1我們並不需要去配置本機的tomcat)
Tomcat started on port(s): 8080 (http) with context path ‘‘
2018-04-14 22:06:26.584 INFO 16752 --- [main] cn.lay.SpringbootApplication: Started SpringbootApplication in 6.587 seconds (JVM running for 8.949)
在瀏覽器輸入
http://localhost:8080/hello
顯示
Hello World
一個簡單的基於springboot的web應用程序就完成了
5、打為jar包運行
pom.xml 文件的打包聲明為:
<packaging>jar</packaging>
打包插件為:
<!-- Package as a executable jar --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
我們運行maven的package命令,在編譯目錄下打包出了一個jar文件;
我們使用命令java -jar 文件名.jar 運行該jar文件(也可以直接使用IDEA開發工具運行)
運行成功以後,瀏覽器輸入http://localhost:8080/hello測試;
最後使用ctrl + c 退出運行
一、快速構建Springboot應用