亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Spring?Boot:Idea從零開始初始化后臺(tái)項(xiàng)目的教程

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

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

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

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

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

1 創(chuàng)建項(xiàng)目

1.1 填寫項(xiàng)目基本信息

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

新建項(xiàng)目

選擇官方初始化器

填寫項(xiàng)目信息

1.2 選擇項(xiàng)目集成功能

完成基本信息配置,在Web,SQL,NoSQL,Ops選項(xiàng)中,選擇對(duì)應(yīng)的模塊依賴,最終選擇如圖以下幾項(xiàng):

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

設(shè)置完成后,點(diǎn)擊下一步,Idea開始初始化項(xiàng)目文件。

集成功能

2 項(xiàng)目基礎(chǔ)配置

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

2.1 gradle文件配置

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

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

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

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ù)庫(kù)配置的日志類com.mysql.cj.log.Slf4JLogger在這個(gè)包中
    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)境文件配置

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

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

#默認(rèn)啟動(dòng)dev環(huán)境
spring.profiles.active=dev
#調(diào)整web后臺(tái)服務(wù)端口為9080,不設(shè)置默認(rèn)為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ù)庫(kù)連接
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ù)庫(kù)登錄名,docker鏡像中的數(shù)據(jù)庫(kù)
spring.datasource.username=root
#數(shù)據(jù)庫(kù)密碼
spring.datasource.password=crane
#本機(jī)docker鏡像中的redis
spring.redis.host=127.0.0.1
#當(dāng)前環(huán)境下日志配置 輸出到控制臺(tái)
logging.config=classpath:logback-dev.xml
#啟用所有類型的健康監(jiān)控
management.endpoints.web.exposure.include=*

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

#mysql數(shù)據(jù)庫(kù)連接
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ù)庫(kù)登錄名,docker鏡像中的數(shù)據(jù)庫(kù)
spring.datasource.username=root
#數(shù)據(jù)庫(kù)密碼
spring.datasource.password=crane
#本機(jī)docker鏡像中的redis
spring.redis.host=127.0.0.1
#當(dāng)前環(huán)境下日志配置 輸出到控制臺(tái)
logging.config=classpath:logback-prod.xml
#啟用所有類型的健康監(jiān)控
management.endpoints.web.exposure.include=*

注意:配置數(shù)據(jù)庫(kù)鏈接spring.datasource.url時(shí)需要注意,當(dāng)前項(xiàng)目引用的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)境對(duì)應(yīng)logback配置文件logback-dev.xml內(nèi)容如下,將日志輸出到控制臺(tá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)境對(duì)應(yīng)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)容如下,目前沒(méi)有任何配置,全部使用默認(rèn)配置。

<?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 簡(jiǎn)單案例

當(dāng)前案例實(shí)現(xiàn)基礎(chǔ)的Redis和MySQL操作,因?yàn)榘咐悄M后端項(xiàng)目搭建過(guò)程,不涉及前端UI展示,所以一些接口使用Postman來(lái)測(cè)試可用性。項(xiàng)目源文件根文件夾下創(chuàng)建控制器類CommonController,用于為web請(qǐng)求提供數(shù)據(jù)響應(yīng),并設(shè)置控制器訪問(wèn)地址,如下

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

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

public class HResponse {
    /**
     * 請(qǐng)求結(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對(duì)Redis進(jìn)行基本操作,這里簡(jiǎn)單提供查詢Redis的key值和設(shè)置Redis的key值兩個(gè)操作,在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("請(qǐng)求獲取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("請(qǐng)求設(shè)置redis key為:{} 的值為 {}", key, value);
        this.redisTemplate.opsForValue().set(key.trim(), value.trim());
        return HResponse.success();
    }

啟動(dòng)redis的docker容器并運(yùn)行當(dāng)前案例,使用Postman發(fā)送請(qǐng)求設(shè)置和查詢r(jià)edis中對(duì)應(yīng)的key值,請(qǐng)求響應(yīng)如下圖

設(shè)置Redis中key值

在這里插入圖片描述

3.2 MySQL案例

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

在這里插入圖片描述

在這里插入圖片描述

3.2.1 JPA方式

構(gòu)造HCompany數(shù)據(jù)庫(kù)映射類和對(duì)應(yīng)的數(shù)據(jù)庫(kù)表訪問(wèn)接口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ù)庫(kù)的方法:

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

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

在這里插入圖片描述

3.2.2 MyBatis方式

使用SqlSession接口訪問(wèn)數(shù)據(jù)庫(kù),創(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中添加通過(guò)MyBatis獲取數(shù)據(jù)的方法,如下

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

重新啟動(dòng)項(xiàng)目,然后通過(guò)Postman訪問(wèn),響應(yīng)如下:

在這里插入圖片描述

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("請(qǐng)求獲取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("請(qǐng)求設(shè)置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)測(cè)

案例啟用了完整的項(xiàng)目監(jiān)測(cè),可通過(guò)http://localhost:9080/actuator查看,每個(gè)監(jiān)測(cè)項(xiàng)都對(duì)應(yīng)相應(yīng)的查看鏈接,如下圖。

在這里插入圖片描述

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

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

在這里插入圖片描述

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

相關(guān)文章

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

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

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

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

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

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

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

    23種設(shè)計(jì)模式(20)java中介者模式

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

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

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

    Java8新特性之方法引用的實(shí)踐指南

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

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

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

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

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

    MybatisPlus實(shí)現(xiàn)分頁(yè)查詢和動(dòng)態(tài)SQL查詢的示例代碼

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

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

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

最新評(píng)論