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

Spring?Boot:Idea從零開始初始化后臺項目的教程

 更新時間:2021年12月21日 14:23:40   作者:晴空排云  
這篇文章主要介紹了Spring?Boot:Idea從零開始初始化后臺項目的教程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

官方提供了Springboot初始化工具可直接在線生成項目文件,然后下載并導入開發(fā)工具中 。這里記錄通過Mac版 IntelliJ IDEA 2019.3.3 (Ultimate Edition)創(chuàng)建Springboot后臺項目的過程,當前Springboot穩(wěn)定版本為2.2.6。

下面的步驟可看做是創(chuàng)建Springboot后臺項目模板,也可以當做個是個Helloworld,主要實現(xiàn)以下功能:

  • 集成MySQL,通過SpringData JPA和MyBatis兩種方式操作數(shù)據(jù)庫
  • 集成Redis內(nèi)存數(shù)據(jù)庫
  • 配置Logback
  • 開啟項目健康監(jiān)測

如需集成其他功能,可在此基礎上添加。上訴MySQL和Redis使用的是《Docker案例:搭建MySQL數(shù)據(jù)庫服務》和《Docker案例:搭建Redis服務》創(chuàng)建的docker容器。

1 創(chuàng)建項目

1.1 填寫項目基本信息

打開Idea創(chuàng)建項目,如下圖:

新建項目

選擇官方初始化器

填寫項目信息

1.2 選擇項目集成功能

完成基本信息配置,在Web,SQL,NoSQL,Ops選項中,選擇對應的模塊依賴,最終選擇如圖以下幾項:

  • Spring Web 用于提供web相關功能
  • Spring Data JPA用于提供數(shù)據(jù)庫相關操作
  • MyBatis Framework用于通過MyBatis操作數(shù)據(jù)庫
  • Spring Data Redis 用于提供Redis相關功能
  • Spring Boot Actuator 用于提供應用的健康監(jiān)測功能

設置完成后,點擊下一步,Idea開始初始化項目文件。

集成功能

2 項目基礎配置

通過上面步驟,已生成項目結(jié)構(gòu)文件,等待開發(fā)環(huán)境自動構(gòu)建好依賴庫后可繼續(xù)后續(xù)的工作。

2.1 gradle文件配置

當前項目使用gradle管理項目依賴,默認情況下,使用官方的依賴庫,國內(nèi)訪問較慢,可替換為阿里云倉庫。在build.gradle文件的repositories節(jié)點下添加阿里云倉庫訪問地址,設置完成后如下

repositories {
    //使用阿里云倉庫,提高國內(nèi)依賴庫下載速度
    maven { url "http://maven.aliyun.com/nexus/content/groups/public" }
    mavenCentral()
}

另外,添加其它常用依賴庫,最終依賴包如下

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.1.2'
    implementation 'com.alibaba:fastjson:1.2.68'
    implementation 'org.apache.commons:commons-lang3:3.10'
    //數(shù)據(jù)庫配置的日志類com.mysql.cj.log.Slf4JLogger在這個包中
    runtime('mysql:mysql-connector-java')
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

2.2 環(huán)境文件配置

官方初始化器默認會在resources資源文件夾下生成一個application.properties文件,這里調(diào)整一下配置文件結(jié)構(gòu)。在resources資源文件夾下創(chuàng)建config文件夾,移動application.properties文件到config文件夾下,同時在config文件夾下創(chuàng)建application-dev.properties文件和application-prod.properties文件,分別對應開發(fā)環(huán)境和線上環(huán)境的配置,可根據(jù)需要增加其它環(huán)境配置文件,文件格式為application-環(huán)境名稱.properties。

最終application.properties文件內(nèi)容如下

#默認啟動dev環(huán)境
spring.profiles.active=dev
#調(diào)整web后臺服務端口為9080,不設置默認為8080
server.port=9080
#mybatis配置文件地址
mybatis.config-location=classpath:mybatis/mybatis-config.xml
#mybatis mapper文件地址
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

application-dev.properties文件內(nèi)容如下

#mysql數(shù)據(jù)庫連接
spring.datasource.url=jdbc:mysql://localhost:3306/crane?autoReconnect=true&characterEncoding=UTF-8&useSSL=false&logger=com.mysql.cj.log.Slf4JLogger&profileSQL=true&maxQuerySizeToLog=8192
#數(shù)據(jù)庫登錄名,docker鏡像中的數(shù)據(jù)庫
spring.datasource.username=root
#數(shù)據(jù)庫密碼
spring.datasource.password=crane
#本機docker鏡像中的redis
spring.redis.host=127.0.0.1
#當前環(huán)境下日志配置 輸出到控制臺
logging.config=classpath:logback-dev.xml
#啟用所有類型的健康監(jiān)控
management.endpoints.web.exposure.include=*

application-prod.properties文件內(nèi)容如下(目前和dev環(huán)境只對日志文件做了區(qū)分,可根據(jù)實際需要調(diào)整)

#mysql數(shù)據(jù)庫連接
spring.datasource.url=jdbc:mysql://localhost:3306/crane?autoReconnect=true&characterEncoding=UTF-8&useSSL=false&logger=com.mysql.cj.log.Slf4JLogger&profileSQL=true&maxQuerySizeToLog=8192
#數(shù)據(jù)庫登錄名,docker鏡像中的數(shù)據(jù)庫
spring.datasource.username=root
#數(shù)據(jù)庫密碼
spring.datasource.password=crane
#本機docker鏡像中的redis
spring.redis.host=127.0.0.1
#當前環(huán)境下日志配置 輸出到控制臺
logging.config=classpath:logback-prod.xml
#啟用所有類型的健康監(jiān)控
management.endpoints.web.exposure.include=*

注意:配置數(shù)據(jù)庫鏈接spring.datasource.url時需要注意,當前項目引用的mysql:mysql-connector-java為8.0.19版本,MySQL日志打印類Slf4JLogger類的路徑為com.mysql.cj.log.Slf4JLogger,較老版本在com.mysql.jdbc.log.Slf4JLogger路徑下。

2.2.1 Logback配置文件

dev環(huán)境對應logback配置文件logback-dev.xml內(nèi)容如下,將日志輸出到控制臺。

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%yellow([%date{yyyy-MM-dd HH:mm:ss.SSS}]) %highlight([%-5level]) %cyan([%thread])
                 - %msg [%logger{1}] \(%file:%line\) %n
            </pattern>
        </encoder>
    </appender>
    <root level="info">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

prod環(huán)境對應logback配置文件logback-prod.xml內(nèi)容如下,將日志輸出到文件。

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>log/hbackend.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>
                log/hbackend-%d{yyyy-MM-dd}.log
            </FileNamePattern>
        </rollingPolicy>
        <encoder>
            <pattern>[%date{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] [%thread] - %msg [%logger{1}]
                \(%file:%line\) %n
            </pattern>
        </encoder>
    </appender>
    <root level="info">
        <appender-ref ref="FILE"/>
    </root>
</configuration>

2.2.2 MyBatis配置文件

mybatis-config.xml文件內(nèi)容如下,目前沒有任何配置,全部使用默認配置。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
    </typeAliases>
</configuration>

3 簡單案例

當前案例實現(xiàn)基礎的Redis和MySQL操作,因為案例是模擬后端項目搭建過程,不涉及前端UI展示,所以一些接口使用Postman來測試可用性。項目源文件根文件夾下創(chuàng)建控制器類CommonController,用于為web請求提供數(shù)據(jù)響應,并設置控制器訪問地址,如下

@RestController
@RequestMapping("/common")
public class CommonController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
}

創(chuàng)建HResponse類,用于構(gòu)造請求的響應結(jié)果,內(nèi)容如下

public class HResponse {
    /**
     * 請求結(jié)果的狀態(tài)
     */
    private int status;
    private String description;
    private Object data;
    public HResponse() {
    }
    public HResponse(int status, String description, Object data) {
        this.status = status;
        this.description = description;
        this.data = data;
    }
    public static HResponse success() {
        return new HResponse(200, "操作成功", null);
    }
    public static HResponse success(String description) {
        return new HResponse(200, description, null);
    }
    public static HResponse success(Object data) {
        return new HResponse(200, "success", data);
    }
    public static HResponse success(String description, Object data) {
        return new HResponse(200, description, data);
    }
    public static HResponse error(String description) {
        return new HResponse(400, description, null);
    }
    public static HResponse error(String description, Object data) {
        return new HResponse(400, description, data);
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

3.1 Redis案例

使用StringRedisTemplate對Redis進行基本操作,這里簡單提供查詢Redis的key值和設置Redis的key值兩個操作,在CommonController中添加代碼如下

	private final StringRedisTemplate redisTemplate;
    private final SqlSession sqlSession;
    public CommonController(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    @PostMapping("/getRedisValue")
    public HResponse getRedisValue(String key) {
        this.logger.info("請求獲取redis key為:{} 的值", key);
        return HResponse.success(new JSONObject().fluentPut("key", key).fluentPut("value", this.redisTemplate.opsForValue().get(key)));
    }
    @PostMapping("/setRedisValue")
    public HResponse getRedisValue(String key, String value) {
        if (StringUtils.isBlank(key)) {
            return HResponse.error("鍵 不能為空");
        }
        if (StringUtils.isBlank(value)) {
            return HResponse.error("值 不能為空");
        }
        this.logger.info("請求設置redis key為:{} 的值為 {}", key, value);
        this.redisTemplate.opsForValue().set(key.trim(), value.trim());
        return HResponse.success();
    }

啟動redis的docker容器并運行當前案例,使用Postman發(fā)送請求設置和查詢redis中對應的key值,請求響應如下圖

設置Redis中key值

在這里插入圖片描述

3.2 MySQL案例

簡單介紹兩種從MySQL查詢數(shù)據(jù)的案例,JPA方式和MyBatis方式。先啟動好MySQL的docker容器,然后創(chuàng)建表h_company并插入一條數(shù)據(jù),最終數(shù)據(jù)表結(jié)果如下圖:

在這里插入圖片描述

在這里插入圖片描述

3.2.1 JPA方式

構(gòu)造HCompany數(shù)據(jù)庫映射類和對應的數(shù)據(jù)庫表訪問接口CompanyRepository,內(nèi)容如下:

@Entity
@Table(name = "h_company")
@Where(clause = "id > 0")
public class HCompany {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String name;
    private String shortName;
    private String address;
    private String tel;
    private String remark;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getShortName() {
        return shortName;
    }
    public void setShortName(String shortName) {
        this.shortName = shortName;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
}
@Repository
@Where(clause = "id > 0")
public interface CompanyRepository extends PagingAndSortingRepository<HCompany, Integer>, JpaRepository<HCompany, Integer> {
}

在控制器CommonController中添加使用CompanyRepository查詢數(shù)據(jù)庫的方法:

    @PostMapping("/getAllCompany")
    public HResponse getAllCompany() {
        return HResponse.success(this.companyRepository.findAll());
    }

使用Postman調(diào)用查詢,響應如下

在這里插入圖片描述

3.2.2 MyBatis方式

使用SqlSession接口訪問數(shù)據(jù)庫,創(chuàng)建company.xmlmapper文件,內(nèi)容如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="company">
    <select id="getAll" resultType="java.util.Map">
        select * from h_company
    </select>
</mapper>

控制器CommonController中添加通過MyBatis獲取數(shù)據(jù)的方法,如下

    @PostMapping("/getAllCompanyByMybatis")
    public HResponse getAllCompanyByMybatis() {
        return HResponse.success(this.sqlSession.selectList("company.getAll"));
    }

重新啟動項目,然后通過Postman訪問,響應如下:

在這里插入圖片描述

3.3 控制器完整代碼

完成以上步驟后,控制器CommonController完整內(nèi)容如下:

@RestController
@RequestMapping("/common")
public class CommonController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private final StringRedisTemplate redisTemplate;
    private final CompanyRepository companyRepository;
    private final SqlSession sqlSession;
    public CommonController(StringRedisTemplate redisTemplate, CompanyRepository companyRepository, SqlSession sqlSession) {
        this.redisTemplate = redisTemplate;
        this.companyRepository = companyRepository;
        this.sqlSession = sqlSession;
    }
    @PostMapping("/getRedisValue")
    public HResponse getRedisValue(String key) {
        this.logger.info("請求獲取redis key為:{} 的值", key);
        return HResponse.success(new JSONObject().fluentPut("key", key).fluentPut("value", this.redisTemplate.opsForValue().get(key)));
    }
    @PostMapping("/setRedisValue")
    public HResponse getRedisValue(String key, String value) {
        if (StringUtils.isBlank(key)) {
            return HResponse.error("鍵 不能為空");
        }
        if (StringUtils.isBlank(value)) {
            return HResponse.error("值 不能為空");
        }
        this.logger.info("請求設置redis key為:{} 的值為 {}", key, value);
        this.redisTemplate.opsForValue().set(key.trim(), value.trim());
        return HResponse.success();
    }
    @PostMapping("/getAllCompany")
    public HResponse getAllCompany() {
        return HResponse.success(this.companyRepository.findAll());
    }
    @PostMapping("/getAllCompanyByMybatis")
    public HResponse getAllCompanyByMybatis() {
        return HResponse.success(this.sqlSession.selectList("company.getAll"));
    }
}

4 健康監(jiān)測

案例啟用了完整的項目監(jiān)測,可通過http://localhost:9080/actuator查看,每個監(jiān)測項都對應相應的查看鏈接,如下圖。

在這里插入圖片描述

5 項目結(jié)構(gòu)

完成以上配置及案例后,項目結(jié)構(gòu)如下圖:

在這里插入圖片描述

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • 聊聊Java 成員變量賦值和構(gòu)造方法誰先執(zhí)行的問題

    聊聊Java 成員變量賦值和構(gòu)造方法誰先執(zhí)行的問題

    這篇文章主要介紹了聊聊Java 成員變量賦值和構(gòu)造方法誰先執(zhí)行的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-10-10
  • java模擬實現(xiàn)微信紅包算法

    java模擬實現(xiàn)微信紅包算法

    這篇文章主要為大家詳細介紹了java實現(xiàn)模擬微信紅包算法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-11-11
  • Java 中 synchronized的用法詳解(四種用法)

    Java 中 synchronized的用法詳解(四種用法)

    Java語言的關鍵字,當它用來修飾一個方法或者一個代碼塊的時候,能夠保證在同一時刻最多只有一個線程執(zhí)行該段代碼。本文給大家介紹java中 synchronized的用法,對本文感興趣的朋友一起看看吧
    2015-11-11
  • 23種設計模式(20)java中介者模式

    23種設計模式(20)java中介者模式

    這篇文章主要為大家詳細介紹了23種設計模式之java中介者模式,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • Java8?CompletableFuture?runAsync學習總結(jié)submit()?execute()等

    Java8?CompletableFuture?runAsync學習總結(jié)submit()?execute()等

    這篇文章主要介紹了Java8?CompletableFuture?runAsync學習總結(jié)submit()?execute()等,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-10-10
  • Java8新特性之方法引用的實踐指南

    Java8新特性之方法引用的實踐指南

    這篇文章主要給大家介紹了關于Java8新特性之方法引用的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03
  • Spring配置文件中parent與abstract的使用

    Spring配置文件中parent與abstract的使用

    這篇文章主要介紹了Spring配置文件中parent與abstract的使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Java實現(xiàn)轉(zhuǎn)跳不同系統(tǒng)使用枚舉加switch的方式示例

    Java實現(xiàn)轉(zhuǎn)跳不同系統(tǒng)使用枚舉加switch的方式示例

    今天小編就為大家分享一篇關于Java實現(xiàn)轉(zhuǎn)跳不同系統(tǒng)使用枚舉加switch的方式示例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • MybatisPlus實現(xiàn)分頁查詢和動態(tài)SQL查詢的示例代碼

    MybatisPlus實現(xiàn)分頁查詢和動態(tài)SQL查詢的示例代碼

    本文主要介紹了MybatisPlus實現(xiàn)分頁查詢和動態(tài)SQL查詢的示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • 使用Maven中的scope總結(jié)

    使用Maven中的scope總結(jié)

    這篇文章主要介紹了使用Maven中的scope總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06

最新評論