Spring?Boot:Idea從零開始初始化后臺(tái)項(xiàng)目的教程
官方提供了Springboot初始化工具可直接在線生成項(xiàng)目文件,然后下載并導(dǎo)入開發(fā)工具中 。這里記錄通過Mac版 IntelliJ IDEA 2019.3.3 (Ultimate Edition)創(chuàng)建Springboot后臺(tái)項(xiàng)目的過程,當(dāng)前Springboot穩(wěn)定版本為2.2.6。
下面的步驟可看做是創(chuàng)建Springboot后臺(tái)項(xiàng)目模板,也可以當(dāng)做個(gè)是個(gè)Helloworld,主要實(shí)現(xiàn)以下功能:
- 集成MySQL,通過SpringData JPA和MyBatis兩種方式操作數(shù)據(jù)庫
- 集成Redis內(nèi)存數(shù)據(jù)庫
- 配置Logback
- 開啟項(xiàng)目健康監(jiān)測
如需集成其他功能,可在此基礎(chǔ)上添加。上訴MySQL和Redis使用的是《Docker案例:搭建MySQL數(shù)據(jù)庫服務(wù)》和《Docker案例:搭建Redis服務(wù)》創(chuàng)建的docker容器。
1 創(chuàng)建項(xiàng)目
1.1 填寫項(xiàng)目基本信息
打開Idea創(chuàng)建項(xiàng)目,如下圖:



1.2 選擇項(xiàng)目集成功能
完成基本信息配置,在Web,SQL,NoSQL,Ops選項(xiàng)中,選擇對應(yīng)的模塊依賴,最終選擇如圖以下幾項(xiàng):
Spring Web用于提供web相關(guān)功能Spring Data JPA用于提供數(shù)據(jù)庫相關(guān)操作MyBatis Framework用于通過MyBatis操作數(shù)據(jù)庫Spring Data Redis用于提供Redis相關(guān)功能Spring Boot Actuator用于提供應(yīng)用的健康監(jiān)測功能
設(shè)置完成后,點(diǎn)擊下一步,Idea開始初始化項(xiàng)目文件。

2 項(xiàng)目基礎(chǔ)配置
通過上面步驟,已生成項(xiàng)目結(jié)構(gòu)文件,等待開發(fā)環(huán)境自動(dòng)構(gòu)建好依賴庫后可繼續(xù)后續(xù)的工作。
2.1 gradle文件配置
當(dāng)前項(xiàng)目使用gradle管理項(xiàng)目依賴,默認(rèn)情況下,使用官方的依賴庫,國內(nèi)訪問較慢,可替換為阿里云倉庫。在build.gradle文件的repositories節(jié)點(diǎn)下添加阿里云倉庫訪問地址,設(shè)置完成后如下
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在這個(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文件,分別對應(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ù)庫連接 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 #本機(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)境只對日志文件做了區(qū)分,可根據(jù)實(shí)際需要調(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 #本機(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ù)庫鏈接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)境對應(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)境對應(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)容如下,目前沒有任何配置,全部使用默認(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 簡單案例
當(dāng)前案例實(shí)現(xiàn)基礎(chǔ)的Redis和MySQL操作,因?yàn)榘咐悄M后端項(xiàng)目搭建過程,不涉及前端UI展示,所以一些接口使用Postman來測試可用性。項(xiàng)目源文件根文件夾下創(chuàng)建控制器類CommonController,用于為web請求提供數(shù)據(jù)響應(yīng),并設(shè)置控制器訪問地址,如下
@RestController
@RequestMapping("/common")
public class CommonController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
}
創(chuàng)建HResponse類,用于構(gòu)造請求的響應(yīng)結(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進(jì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("請求獲取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("請求設(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ā)送請求設(shè)置和查詢r(jià)edis中對應(yīng)的key值,請求響應(yīng)如下圖


3.2 MySQL案例
簡單介紹兩種從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ù)庫映射類和對應(yīng)的數(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)用查詢,響應(yīng)如下

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"));
}
重新啟動(dòng)項(xiàng)目,然后通過Postman訪問,響應(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("請求獲取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("請求設(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)測
案例啟用了完整的項(xiàng)目監(jiān)測,可通過http://localhost:9080/actuator查看,每個(gè)監(jiān)測項(xiàng)都對應(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)造方法誰先執(zhí)行的問題
這篇文章主要介紹了聊聊Java 成員變量賦值和構(gòu)造方法誰先執(zhí)行的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
Java 中 synchronized的用法詳解(四種用法)
Java語言的關(guān)鍵字,當(dāng)它用來修飾一個(gè)方法或者一個(gè)代碼塊的時(shí)候,能夠保證在同一時(shí)刻最多只有一個(gè)線程執(zhí)行該段代碼。本文給大家介紹java中 synchronized的用法,對本文感興趣的朋友一起看看吧2015-11-11
Java8?CompletableFuture?runAsync學(xué)習(xí)總結(jié)submit()?execute()等
這篇文章主要介紹了Java8?CompletableFuture?runAsync學(xué)習(xí)總結(jié)submit()?execute()等,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-10-10
Java實(shí)現(xiàn)轉(zhuǎn)跳不同系統(tǒng)使用枚舉加switch的方式示例
今天小編就為大家分享一篇關(guān)于Java實(shí)現(xiàn)轉(zhuǎn)跳不同系統(tǒng)使用枚舉加switch的方式示例,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2018-12-12
MybatisPlus實(shí)現(xiàn)分頁查詢和動(dòng)態(tài)SQL查詢的示例代碼
本文主要介紹了MybatisPlus實(shí)現(xiàn)分頁查詢和動(dòng)態(tài)SQL查詢的示例代碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09

