欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot項目開發(fā)常用技術(shù)整合

 更新時間:2021年08月10日 17:01:53   作者:大唐雨夜  
今天給大家分享springboot項目開發(fā)常用技術(shù)整合,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧

1 創(chuàng)建一個springboot demo

請?zhí)砑訄D片描述

pom.xml添加springboot相關(guān)依賴。

1.1 創(chuàng)建Restful接口

springmvc構(gòu)造并且返回一個json對象:

  • 在類上加@Controller注解
  • 在方法上加@ResponseBody

springboot構(gòu)造并且返回一個json對象:

  • 在類上加@RestController注解(@RestController = @Controller + @ResponseBody)

 2 接口返回通用JSON對象

2.1 構(gòu)建通用返回對象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對象pojo對象屬性進行處理,例如隱藏、格式化輸出、默認(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開發(fā)環(huán)境熱部署

devtools可以實現(xiàn)頁面熱部署(即頁面修改后會立即生效,可以直接在application.properties文件中配置spring.thymeleaf.cache=false來實現(xiàn)),實現(xiàn)類文件熱部署(類文件修改后不會立即生效),實現(xiàn)對屬性文件的熱部署。
即devtools會監(jiān)聽classpath下的文件變動,并且會立即重啟應(yīng)用(發(fā)生在保存時機),注意:因為其采用的虛擬機機制,該項重啟是很快的 。

(1)base classloader (Base類加載器):加載不改變的Class,例如:第三方提供的jar包。
(2)restart classloader(Restart類加載器):加載正在開發(fā)的Class。
為什么重啟很快,因為重啟的時候只是加載了在開發(fā)的Class,沒有重新加載第三方的jar包。

默認(rèn)情況下,/META-INF/maven,/META-INF/resources,/resources,/static,/templates,/public這些文件夾下的文件修改不會使應(yīng)用重啟,但是會重新加載(devtools內(nèi)嵌了一個LiveReload server,當(dāng)資源發(fā)生改變時,瀏覽器刷新)。

依賴

<!--熱部署-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <!-- optional=true, 依賴不會傳遞, 該項目依賴devtools;
        之后依賴boot項目的項目如果想要使用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熱部署沒有生效,進行以下操作。

  1. 開啟自動編譯:Files——Settings——Build,Execution,Deployment——Compiler
  2. 使用shift+ctrl+alt+/,選擇Registry。

請?zhí)砑訄D片描述

4 資源文件屬性配置

 4.1 資源文件中的屬性配置與映射到實體類

// 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)備好前端頁面放到配置dir目錄下。測試代碼:

/**
 * 測試向頁面注入屬性
 *
 * @param modelMap
 * @return
 */
@RequestMapping("/index")
public String index(ModelMap modelMap) {
    modelMap.addAttribute("resource", resource);
    return "freemarker/index";
}

/**
 * 測試多層路徑,不需要加后綴
 *
 * @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)閉緩存, 即時刷新, 上線生產(chǎn)環(huán)境需要改為true
spring.thymeleaf.cache=false

## 設(shè)置靜態(tài)文件目錄,js、css等
spring.mvc.static-path-pattern=/static/**

內(nèi)容包含:

  • 對象屬性獲取與頁面屬性設(shè)置 th:id
  • html內(nèi)容替換 th:text/utext
  • 根元素設(shè)置 th:object
  • 超鏈接 th:href
  • form th:action="@{/th/postform}"
  • 語法:比較、循環(huán)遍歷、switch

5.2.1 集成i18n屬性配置

i18n對程序來說,在不修改內(nèi)部代碼的情況下,能根據(jù)不同語言及地區(qū)顯示相應(yīng)的界面。

############################################################# i18n 資源配置############################################################spring.messages.basename=i18n/messages# 緩存時間 單位 sspring.messages.cache-duration=1spring.messages.encoding=UTF-8

指定目錄下配置屬性

roles.manager=managerroles.superadmin=lzp

6 全局捕獲異常

頁面跳轉(zhuǎn)形式:接口直接返回一個頁面ModelAndView。

ajax形式:返回統(tǒng)一響應(yīng)對象,前端解析對象獲取數(shù)據(jù)。

統(tǒng)一返回異常的形式

@ControllerAdvicepublic class ExceptionErrorHandler {    /**     * 異常跳轉(zhuǎn)頁面     */    public static final String ERROR_VIEW = "error";    @ExceptionHandler(value = Exception.class)    public Object errorHandler(HttpServletRequest request,                               HttpServletResponse response,                               Exception e) throws Exception {        // 后臺打印日志        e.printStackTrace();        if (isAjax(request)) {            // 返回ajax響應(yīng)            return JSONResult.errorException(e.getMessage());        } else {            // 返回頁面            ModelAndView mav = new ModelAndView();            mav.addObject("exception", e);            mav.addObject("url", request.getRequestURL());            // 把錯誤頁面返回給前端,而不是使用springboot自帶的頁面            mav.setViewName(ERROR_VIEW);            return mav;        }    }    /**     * 判斷請求是否是ajax請求     *     * @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以及分頁

7.1 mybatis-generator的使用

  1. 添加mybatis、mysql、數(shù)據(jù)源、tkmybatis、pagehelper依賴。如果用hikari,默認(rèn)支持不需要引用依賴。
  2. 添加application.properties相關(guān)配置。
  3. 配置generatorConfig.xml pojo、mapper、xml、表等
  4. 使用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 如果沒有事務(wù),則創(chuàng)建事務(wù);已有則加入到當(dāng)前事務(wù)。

SUPPORTS 如果已有事務(wù),加入當(dāng)前事務(wù);沒有也可以。

9 集成Redis

添加pom和application.properties配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

使用StringRedisTemplete操作數(shù)據(jù)。

10 集成定時功能

// 啟動定時操作
@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í)行使用場景

  • 發(fā)送短信、發(fā)送郵件
  • App消息推送
  • 節(jié)省運維淩晨發(fā)布任務(wù)時間提供效率
//開啟異步調(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耗時:" + (end - start) + "毫秒");
        return new AsyncResult<>(true);
    }
}

12 配置攔截器

攔截器,訪問某個請求前后進行攔截。

注冊配置

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Bean
    public UserTokenInterceptor userTokenInterceptor() {
        return new UserTokenInterceptor();
    }

    /**
     * 注冊攔截器
     *
     * @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項目開發(fā)常用技術(shù)整合的文章就介紹到這了,更多相關(guān)SpringBoot開發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • CommonMark 使用教程:將 Markdown 語法轉(zhuǎn)成 Html

    CommonMark 使用教程:將 Markdown 語法轉(zhuǎn)成 Html

    這篇文章主要介紹了CommonMark 使用教程:將 Markdown 語法轉(zhuǎn)成 Html,這個技巧我們做任何網(wǎng)站都可以用到,而且非常好用。,需要的朋友可以參考下
    2019-06-06
  • Spring實戰(zhàn)之使用c:命名空間簡化配置操作示例

    Spring實戰(zhàn)之使用c:命名空間簡化配置操作示例

    這篇文章主要介紹了Spring實戰(zhàn)之使用c:命名空間簡化配置操作,結(jié)合實例形式詳細(xì)分析了Spring使用c:命名空間簡化配置的相關(guān)接口與配置操作技巧,需要的朋友可以參考下
    2019-12-12
  • Java中隨機函數(shù)變換的示例詳解

    Java中隨機函數(shù)變換的示例詳解

    這篇文章主要為大家詳細(xì)介紹了Java中隨機函數(shù)的變換,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)Java有一定的幫助,感興趣的可以了解一下
    2022-08-08
  • SpringBoot使用Mybatis&Mybatis-plus文件映射配置方法

    SpringBoot使用Mybatis&Mybatis-plus文件映射配置方法

    這篇文章主要介紹了SpringBoot使用Mybatis&Mybatis-plus文件映射配置方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-05-05
  • Spring Boot如何實現(xiàn)定時任務(wù)的動態(tài)增刪啟停詳解

    Spring Boot如何實現(xiàn)定時任務(wù)的動態(tài)增刪啟停詳解

    這篇文章主要給大家介紹了關(guān)于Spring Boot如何實現(xiàn)定時任務(wù)的動態(tài)增刪啟停的相關(guān)資料,文中通過示例代碼以及圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • springboot 在xml里讀取yml的配置信息的示例代碼

    springboot 在xml里讀取yml的配置信息的示例代碼

    這篇文章主要介紹了springboot 在xml里讀取yml的配置信息的示例代碼,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-09-09
  • 聊聊Java三種常見的分布式鎖

    聊聊Java三種常見的分布式鎖

    目前分布式鎖的實現(xiàn)方案主要包括三種,本文就來介紹一下這三種常見的分布式鎖以及這三種鎖的性能等,具有一定的參考價值,感興趣的可以了解一下
    2023-06-06
  • java中同類對象之間的compareTo()和compare()方法對比分析

    java中同類對象之間的compareTo()和compare()方法對比分析

    這篇文章主要介紹了java中同類對象之間的compareTo()和compare()方法對比分析,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • idea常用配置之注釋快捷鍵方式

    idea常用配置之注釋快捷鍵方式

    這篇文章主要介紹了idea常用配置之注釋快捷鍵方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • 淺談JAVA工作流的優(yōu)雅實現(xiàn)方式

    淺談JAVA工作流的優(yōu)雅實現(xiàn)方式

    這篇文章主要介紹了淺談JAVA工作流的優(yōu)雅實現(xiàn)方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-11-11

最新評論