最近由於項目須要接觸了springboot,而後被其快速零配置的特色驚呆了。關於springboot相關的介紹我就不贅述了,你們自行百度google。java
1、pom配置web
首先,創建一個maven項目,修改pom.xml文件,添加parent依賴。spring
<parent>json
<groupId>org.springframework.boot</groupId>瀏覽器
<artifactId>spring-boot-starter-parent</artifactId>tomcat
<version>1.4.2.RELEASE</version>springboot
</parent>服務器
spring-boot-starter-parent會自動爲咱們引入spring相關的依賴。微信
再看dependencies節點:mybatis
咱們須要引入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>
2、程序入口
在一級包路徑下,好比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:啓用註解式事務。
3、配置
在項目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
4、頁面以及靜態資源(默認)
頁面:/resources/templates/
靜態資源:/resources/static/
5、控制器
控制器依然使用@Controller註解,或者@RestController(返回json,Controller和ResponseBody合體),咱們在templates下新建一個index.vm視圖文件,輸出hello,world!
6、打包,啓動
使用mvn clean package將應用打成一個jar包,好比test.jar。
在命令行執行命令:java -jar test.jar(也能夠在IDE中直接執行main方法)
恭喜你,成功啓動!
在瀏覽器輸入localhost:8081/test/看一下效果:
快來感覺springboot帶給你的快感吧!
7、優缺點
優勢:簡化配置,快速構建應用。我的感受比較適合作微服務。
缺點:坑不少啊,踩過才知道,對spring平臺不瞭解的同窗慎用,仍是老老實實的本身配置吧。
下一篇我會來介紹springboot集成mybatis。
關注老薑談技術,微信號:helojava,或者掃描下面二維碼。
代碼改變世界。