初識Springboot框架
什麼是springboot?它和春天的區別是什麼?
springboot相比彈簧來說它“約定大於配置”,相信大家都被彈簧的複雜的配置給煩惱過,springboot提供一個免配置的解決方案,無需使用大量的XML配置檔案來配置專案,讓開發更簡單,並且Spring Boot並不重複造輪子,而且在原有Spring的框架基礎上封裝了一層。換句話說,Spring Boot是一個容器。
SpringBoot官網:Spring Projects
Spring Boot官方推薦使用Maven或Gradle來構建專案本篇將使用maven來構建專案。
建立第一個Spring Boot專案
這裡就以helloWolrd為例子
springboot提供兩種建立的專案的方式,本文章通過springboot的官網來建立第一個springboot專案地址如下。
https://start.spring.io/start.spring.io
以maven構建專案 - > Generator Project建立第一個springboot專案
匯入程式碼到eclipse - > maven install構建專案
相關的依賴檔案
的的pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
建立一個控制器類位於例子的子包下HelloController中:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @SpringBootApplication public class HelloController { @RequestMapping("hello") String hello() { return "Hello World!"; } }
執行主方法(該方法自動生成不需要手寫)
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
(需要安裝STS工具來執行)
Springboot的啟動需要eclipse外掛sts下載方式幫助
- > marketplace - >熱門
選擇springbootTools工具 - >安裝安裝sts外掛
springboot會使用內嵌的tomcat的伺服器來啟動,啟動成功後
瀏覽器訪問:http:// localhost:8080 / hello
即可看到我們的歡迎頁面了。
屬性以及yaml
springboot中只有一個配置檔案就是屬性或者yaml
springboot中對配置檔案都有預設值,我們也可以通過application.properties
來定義我們自己的配置
在資源目錄下的application.xml中裡定義。
常用的註解
@SpringBootConfiguration 表示springboot的常用的配置註解
EnableAutoConfiguration 表示自動註解
@ComponentScan元件掃描 用於configuration配置類的掃描指令,可以對指定的包進行掃描。
@Configuration 配置註解類
如果我們想用程式碼來配置,則需要在這個類上加入這個註解
整合其他開源框架mybatis
Spring Boot是一個容器,它將很多第三方框架都進行了整合,我們在實際專案中用到哪個模組,再引入哪個模組。比如我們專案中的持久化框架用MyBatis,則在pom .xml新增如 下依賴:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
在application.xml新增以下配置檔案
datasource:url:jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=UTF-8&useSSL=trueusername: root password: root driverClassName: com.mysql.jdbc.Driver #mybatis mybatis.type-aliases-package=com.example.demo.pojo mybatis.mapper-locations=classpath:mapper/*.xml #mapper #mappers mapper.mappers=com.example.utils.MyMapper mapper.not-empty=false mapper.identity=MYSQL
更多的配置資訊可以參照官網 SpringBoot官網:Spring Projects。
統一異常處理類
我們在通常需要捕捉異常,並且友好的對使用者進行提示,如果在頁面上報出異常資訊
那麼對於使用者來說是一種很不友好的體驗,如果單單在每一個程式碼上都捕捉異常然後丟擲
異常頁面,程式碼就會顯得特別的臃腫,全域性異常處理類就出現了。 @ControllerAdvice,不用任何的配置,只要把這個類放在專案中,Spring能掃描到的地方。就可以實現全域性異常的回撥。@ExceptionHandler標註處理異常的方法
package com.example.demo.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import com.example.demo.pojo.XYFJSONResult;
@ControllerAdvice
/**
* 全域性異常捕獲
*/
public class XuYuanFengExceptionHandler {
public static final String ERROR_VIEW = "error";
@ExceptionHandler(value = Exception.class)
public Object errorHandler(HttpServletRequest request, HttpServletResponse resp, Exception e) throws Exception {
e.printStackTrace();
if (isAjax(request)) {
new XYFJSONResult();
return XYFJSONResult.errorException(e.getMessage());
} else {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", request.getRequestURL());
mav.setViewName(ERROR_VIEW);
return e;
}
}
public static boolean isAjax(HttpServletRequest request) {
return (request.getHeaders("X-Requested-With") != null
&& "XMLHttpReqeust".equals(request.getHeaders("X-Requested-With").toString()));
}
}
錯誤頁面的程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 style="color:red">發生異常</h1>
<div th:text="${e}"> </div>
</body>
</html>
單元測試
@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class TestDB {
@Test
public void test(){
}
}
模板引擎
springboot 支援 FreeMark、Thymeleaf等模板引擎 來開發前後分離的專案。同時也支援jsp等模板引擎。
整合Thymeleaf
相關的pom檔案
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在application,xml中配置thymeleaf 的基本格式
spring.thymeleaf.prefix = classpath:/ templates /
spring.thymeleaf.suffix = .html
spring.thymeleaf.mode = HTML5
spring.thymeleaf.encoding = UTF-8
spring.thymeleaf.servlet.content-type = text / html; charset = utf-8
spring.thymeleaf.cache = false
spring.mvc.static-path-pattern = / static / **
spring.mvc.static-path-pattern = / static / **
表示對映的thymeleaf的路徑在靜目錄下
thymeleaf的基本語法參考
http://link.zhihu.com/?target=https%3A//blog.csdn.net/RAVEEE/article/details/83378445