快速搭建springboot項目,被其快速零配置的特點驚呆了

最近因為項目需要接觸了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>

spring-boot-starter-parent會自動為我們引入spring相關的依賴。

再看dependencies節點:

快速搭建springboot項目,被其快速零配置的特點驚呆了

  • 我們需要引入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>

二、程序入口

在一級包路徑下,比如com.xxx,新建一個Application.java。

快速搭建springboot項目,被其快速零配置的特點驚呆了

解釋一下註解:

  • @Configuration:指出該類是 Bean 配置的信息源,相當於XML中的<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方法)

快速搭建springboot項目,被其快速零配置的特點驚呆了

恭喜你,成功啟動!

在瀏覽器輸入localhost:8081/test/看一下效果:

快速搭建springboot項目,被其快速零配置的特點驚呆了

快來感受springboot帶給你的快感吧!


分享到:


相關文章: