Springboot搭建web項目,springboot搭建web
最近因為項目需要接觸了springboot,然後被其快速零配置的特點驚呆了。關於springboot相關的介紹我就不贅述了,大家自行百度google。
一、pom配置
首先,建立一個maven項目,修改pom.xml檔案,添加parent依賴。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.2.RELEASE</version>
</parent>
spring-boot-starter-parent會自動為我們引入spring相關的依賴。
再看dependencies節點:
-
我們需要引入starter-web,這是開發web項目必須的依賴,springboot預設整合了tomcat伺服器,在這裡排除了tomcat,引入了NIO伺服器undertow。
-
springboot預設伺服器連接埠8080,可以自行修改,後面會介紹。
-
視圖引擎選擇velocity,引入starter-velocity即可,具體配置後面介紹。
-
引入maven外掛程式:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
二、程式入口
在一級包路徑下,比如com.xxx,建立一個Application.java。
解釋一下註解:
-
@Configuration:指出該類是 Bean 配置的資訊源,相當於XML中的<beans></beans>,一般加在主類上。
-
@EnableAutoConfiguration:讓 SpringBoot 根據應用所聲明的依賴來對 Spring 架構進行自動設定,由於 spring-boot-starter-web 添加了Tomcat和Spring MVC,所以auto-configuration將假定你正在開發一個web應用並相應地對Spring進行設定
-
@ ComponentScan:表示將該類自動探索(掃描)並註冊為Bean,可以自動收集所有的Spring組件(@Component , @Service , @Repository , @Controller 等),包括@Configuration類。
-
@SpringBootApplication: @EnableAutoConfiguration、@ComponentScan和@Configuration的合集。
-
@ EnableTransactionManagement:啟用註解式事務。
三、配置
在項目resources目錄下建立application.properties檔案,springboot預設會讀取該設定檔,當然你也可以建立一個名為application.yml檔案。
3.1 伺服器
server.port=8081
server.context-path=/test
將伺服器連接埠修改為8081,並制定根為test,其他配置請自行挖掘。
3.2 日誌
springboot預設使用logback,當然你可以使用別的日誌,如log4j2。
logging.config=classpath:logback.xml
logging.level.org.springframework.web=DEBUG
指定日誌設定檔位置和記錄層級
3.3 模板引擎
使用yml檔案進行配置,我們看到這種縮排式的配置,可以省略很多重複性的語句。
spring:
velocity:
charset: UTF-8
properties:
input:
encoding: UTF-8
output:
encoding: UTF-8
toolbox-config-location:/templates/toolbox.xml
四、頁面以及靜態資源(預設)
頁面:/resources/templates/
靜態資源:/resources/static/
五、控制器
控制器依然使用@Controller註解,或者@RestController(返回json,Controller和ResponseBody合體),我們在templates下建立一個index.vm視圖檔案,輸出hello,world!
六、打包,啟動
使用mvn clean package將應用打成一個jar包,比如test.jar。
在命令列執行命令:java -jar test.jar(也可以在IDE中直接執行main方法)
恭喜你,成功啟動!
在瀏覽器輸入localhost:8081/test/看一下效果:
快來感受springboot帶給你的快感吧!
七、優缺點
下一篇我會來介紹springboot整合mybatis。
關注老薑談技術,號:helojava,或者掃描下面二維碼。
代碼改變世界。