SpringBoot項(xiàng)目開(kāi)發(fā)常用技術(shù)整合
1 創(chuàng)建一個(gè)springboot demo

pom.xml添加springboot相關(guān)依賴。
1.1 創(chuàng)建Restful接口
springmvc構(gòu)造并且返回一個(gè)json對(duì)象:
- 在類上加@Controller注解
- 在方法上加@ResponseBody
springboot構(gòu)造并且返回一個(gè)json對(duì)象:
- 在類上加@RestController注解(@RestController = @Controller + @ResponseBody)
2 接口返回通用JSON對(duì)象
2.1 構(gòu)建通用返回對(duì)象JSONResult
參考gitee代碼
public class JSONResult {
private Integer status; // 響應(yīng)狀態(tài)
private String msg; // 響應(yīng)消息
private Object data; // 數(shù)據(jù)
/*靜態(tài)工廠方法*/
public static JSONResult build(Integer status, String msg, Object data) {
return new JSONResult(status, msg, data);
}
public static JSONResult ok(Object data) {
return new JSONResult(data);
}
}
2.2 使用Jackson
使用Jackson對(duì)象pojo對(duì)象屬性進(jìn)行處理,例如隱藏、格式化輸出、默認(rèn)值。
public class User {
private String name;
@JsonIgnore
private String password;
private Integer age;
@JsonFormat(pattern = "yyyy-MM-dd hh:mm:ss", locale = "zh", timezone = "GMT+8")
private Date birthday;
@JsonInclude(JsonInclude.Include.NON_NULL)
private String desc;
}
3 SpringBoot開(kāi)發(fā)環(huán)境熱部署
devtools可以實(shí)現(xiàn)頁(yè)面熱部署(即頁(yè)面修改后會(huì)立即生效,可以直接在application.properties文件中配置spring.thymeleaf.cache=false來(lái)實(shí)現(xiàn)),實(shí)現(xiàn)類文件熱部署(類文件修改后不會(huì)立即生效),實(shí)現(xiàn)對(duì)屬性文件的熱部署。
即devtools會(huì)監(jiān)聽(tīng)classpath下的文件變動(dòng),并且會(huì)立即重啟應(yīng)用(發(fā)生在保存時(shí)機(jī)),注意:因?yàn)槠洳捎玫奶摂M機(jī)機(jī)制,該項(xiàng)重啟是很快的 。
(1)base classloader (Base類加載器):加載不改變的Class,例如:第三方提供的jar包。
(2)restart classloader(Restart類加載器):加載正在開(kāi)發(fā)的Class。
為什么重啟很快,因?yàn)橹貑⒌臅r(shí)候只是加載了在開(kāi)發(fā)的Class,沒(méi)有重新加載第三方的jar包。
默認(rèn)情況下,/META-INF/maven,/META-INF/resources,/resources,/static,/templates,/public這些文件夾下的文件修改不會(huì)使應(yīng)用重啟,但是會(huì)重新加載(devtools內(nèi)嵌了一個(gè)LiveReload server,當(dāng)資源發(fā)生改變時(shí),瀏覽器刷新)。
依賴
<!--熱部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<!-- optional=true, 依賴不會(huì)傳遞, 該項(xiàng)目依賴devtools;
之后依賴boot項(xiàng)目的項(xiàng)目如果想要使用devtools, 需要重新引入 -->
<optional>true</optional>
</dependency>
配置
#熱部署生效 spring.devtools.restart.enabled=true #設(shè)置重啟的目錄 spring.devtools.restart.additional-paths=src/main/java #classpath目錄下的WEB-INF文件夾內(nèi)容修改不重啟 spring.devtools.restart.exclude=WEB-INF/** #spring.devtools.restart.exclude=static/**,public/**
如果IDEA devtools熱部署沒(méi)有生效,進(jìn)行以下操作。
- 開(kāi)啟自動(dòng)編譯:Files——Settings——Build,Execution,Deployment——Compiler
- 使用shift+ctrl+alt+/,選擇Registry。

4 資源文件屬性配置
4.1 資源文件中的屬性配置與映射到實(shí)體類
// com.lzp.opensource.name=lzp
@Configuration
@1(prefix = "com.lzp.opensource")
@PropertySource(value = "classpath:resource.properties")
public class Resource {
private String name;
private String website;
private String language;
}
4.2 Server和Tomcat配置(詳細(xì)配置參考Gitee)
server.port=8088 server.tomcat.uri-encoding=UTF-8
5 SpringBoot整合模板引擎
5.1 集成freemarker
添加依賴、配置,準(zhǔn)備好前端頁(yè)面放到配置dir目錄下。測(cè)試代碼:
/**
* 測(cè)試向頁(yè)面注入屬性
*
* @param modelMap
* @return
*/
@RequestMapping("/index")
public String index(ModelMap modelMap) {
modelMap.addAttribute("resource", resource);
return "freemarker/index";
}
/**
* 測(cè)試多層路徑,不需要加后綴
*
* @return
*/
@RequestMapping("/center")
public String center() {
return "freemarker/center/center";
}
5.2 集成thymeleaf
############################################################ # thymeleaf 靜態(tài)資源配置 ############################################################ spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html # 關(guān)閉緩存, 即時(shí)刷新, 上線生產(chǎn)環(huán)境需要改為true spring.thymeleaf.cache=false ## 設(shè)置靜態(tài)文件目錄,js、css等 spring.mvc.static-path-pattern=/static/**
內(nèi)容包含:
- 對(duì)象屬性獲取與頁(yè)面屬性設(shè)置 th:id
- html內(nèi)容替換 th:text/utext
- 根元素設(shè)置 th:object
- 超鏈接 th:href
- form th:action="@{/th/postform}"
- 語(yǔ)法:比較、循環(huán)遍歷、switch
5.2.1 集成i18n屬性配置
i18n對(duì)程序來(lái)說(shuō),在不修改內(nèi)部代碼的情況下,能根據(jù)不同語(yǔ)言及地區(qū)顯示相應(yīng)的界面。
############################################################# i18n 資源配置############################################################spring.messages.basename=i18n/messages# 緩存時(shí)間 單位 sspring.messages.cache-duration=1spring.messages.encoding=UTF-8
指定目錄下配置屬性
roles.manager=managerroles.superadmin=lzp
6 全局捕獲異常
頁(yè)面跳轉(zhuǎn)形式:接口直接返回一個(gè)頁(yè)面ModelAndView。
ajax形式:返回統(tǒng)一響應(yīng)對(duì)象,前端解析對(duì)象獲取數(shù)據(jù)。
統(tǒng)一返回異常的形式
@ControllerAdvicepublic class ExceptionErrorHandler { /** * 異常跳轉(zhuǎn)頁(yè)面 */ public static final String ERROR_VIEW = "error"; @ExceptionHandler(value = Exception.class) public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception { // 后臺(tái)打印日志 e.printStackTrace(); if (isAjax(request)) { // 返回ajax響應(yīng) return JSONResult.errorException(e.getMessage()); } else { // 返回頁(yè)面 ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", request.getRequestURL()); // 把錯(cuò)誤頁(yè)面返回給前端,而不是使用springboot自帶的頁(yè)面 mav.setViewName(ERROR_VIEW); return mav; } } /** * 判斷請(qǐng)求是否是ajax請(qǐng)求 * * @param httpRequest * @return */ public static boolean isAjax(HttpServletRequest httpRequest) { return (httpRequest.getHeader("X-Requested-With") != null && "XMLHttpRequest" .equals(httpRequest.getHeader("X-Requested-With").toString())); }}
7 集成mybatis以及分頁(yè)
7.1 mybatis-generator的使用
- 添加mybatis、mysql、數(shù)據(jù)源、tkmybatis、pagehelper依賴。如果用hikari,默認(rèn)支持不需要引用依賴。
- 添加application.properties相關(guān)配置。
- 配置generatorConfig.xml pojo、mapper、xml、表等
- 使用GeneratorDisplay生成文件。
Application添加mapper掃描配置
//掃描 mybatis mapper 包路徑@MapperScan(basePackages = "com.lzp.mapper")// 掃描指定位置@ComponentScan({"com.lzp", "org.n3r.idworker"})@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
7.2 tkmybatis的一些用法
使用通用Mapper可以節(jié)省很多代碼
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {}public interface SysUserMapper extends MyMapper<SysUser> {}
調(diào)用
userMapper.insert(user);userMapper.updateByPrimaryKeySelective(user);@Overridepublic List<SysUser> queryUserList(SysUser user) { // 條件 Example example = new Example(SysUser.class); Example.Criteria criteria = example.createCriteria(); criteria.andLike("username", "%" + user.getUsername() + "%"); return userMapper.selectByExample(example);}
8 聲明式事務(wù)支持
@Transactional(propagation = Propagation.REQUIRED)@Overridepublic void saveUserTransactional(SysUser user) { userMapper.insert(user); int i = 1 / 0; user.setIsDelete(1); userMapper.updateByPrimaryKeySelective(user);}
REQUIRED 如果沒(méi)有事務(wù),則創(chuàng)建事務(wù);已有則加入到當(dāng)前事務(wù)。
SUPPORTS 如果已有事務(wù),加入當(dāng)前事務(wù);沒(méi)有也可以。
9 集成Redis
添加pom和application.properties配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
使用StringRedisTemplete操作數(shù)據(jù)。
10 集成定時(shí)功能
// 啟動(dòng)定時(shí)操作
@EnableScheduling
public class Application {...}
調(diào)度類
@Component
public class SchedulerJob {
@Scheduled(fixedRate = 3000)
public void printLog() {
System.out.println("每隔3秒");
}
@Scheduled(cron = "0/1 * * * * ?")
public void printLogInterval() {
System.out.println("每隔1秒");
}
}
11 異步任務(wù)
Spring Boot異步執(zhí)行使用場(chǎng)景
- 發(fā)送短信、發(fā)送郵件
- App消息推送
- 節(jié)省運(yùn)維淩晨發(fā)布任務(wù)時(shí)間提供效率
//開(kāi)啟異步調(diào)用方法
@EnableAsync
public class Application {
結(jié)合
@Component
public class AsyncTask {
@Async
public Future<Boolean> doTask11() throws Exception {
long start = System.currentTimeMillis();
Thread.sleep(1000);
long end = System.currentTimeMillis();
System.out.println("任務(wù)1耗時(shí):" + (end - start) + "毫秒");
return new AsyncResult<>(true);
}
}
12 配置攔截器
攔截器,訪問(wèn)某個(gè)請(qǐng)求前后進(jìn)行攔截。
注冊(cè)配置
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public UserTokenInterceptor userTokenInterceptor() {
return new UserTokenInterceptor();
}
/**
* 注冊(cè)攔截器
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userTokenInterceptor())
.addPathPatterns("/testIntercept")
.addPathPatterns("/hello")
.addPathPatterns("/shopcart/add")
}
}
UserTokenInterceptor參考詳細(xì)代碼。
代碼地址
源碼地址:https://gitee.com/dtyytop/initialdemo
到此這篇關(guān)于SpringBoot項(xiàng)目開(kāi)發(fā)常用技術(shù)整合的文章就介紹到這了,更多相關(guān)SpringBoot開(kāi)發(fā)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
CommonMark 使用教程:將 Markdown 語(yǔ)法轉(zhuǎn)成 Html
這篇文章主要介紹了CommonMark 使用教程:將 Markdown 語(yǔ)法轉(zhuǎn)成 Html,這個(gè)技巧我們做任何網(wǎng)站都可以用到,而且非常好用。,需要的朋友可以參考下2019-06-06
Spring實(shí)戰(zhàn)之使用c:命名空間簡(jiǎn)化配置操作示例
這篇文章主要介紹了Spring實(shí)戰(zhàn)之使用c:命名空間簡(jiǎn)化配置操作,結(jié)合實(shí)例形式詳細(xì)分析了Spring使用c:命名空間簡(jiǎn)化配置的相關(guān)接口與配置操作技巧,需要的朋友可以參考下2019-12-12
SpringBoot使用Mybatis&Mybatis-plus文件映射配置方法
這篇文章主要介紹了SpringBoot使用Mybatis&Mybatis-plus文件映射配置方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-05-05
Spring Boot如何實(shí)現(xiàn)定時(shí)任務(wù)的動(dòng)態(tài)增刪啟停詳解
這篇文章主要給大家介紹了關(guān)于Spring Boot如何實(shí)現(xiàn)定時(shí)任務(wù)的動(dòng)態(tài)增刪啟停的相關(guān)資料,文中通過(guò)示例代碼以及圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
springboot 在xml里讀取yml的配置信息的示例代碼
這篇文章主要介紹了springboot 在xml里讀取yml的配置信息的示例代碼,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09
java中同類對(duì)象之間的compareTo()和compare()方法對(duì)比分析
這篇文章主要介紹了java中同類對(duì)象之間的compareTo()和compare()方法對(duì)比分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09
淺談JAVA工作流的優(yōu)雅實(shí)現(xiàn)方式
這篇文章主要介紹了淺談JAVA工作流的優(yōu)雅實(shí)現(xiàn)方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11

