序言
從簡入深的使用SpringBoot搭建一個Web專案,同時也包括一些小的問題,第一篇博文是以較為簡單的方式完成一個可以連接資料庫的Springboot web程式,之前自己學習的時候看網上的教程總是感覺有點太大,我只是想最簡單的搭建一個可以運行的專案,之后再去深究細節,每個教程的配置還都不一樣,讓我不知所措,所以我就寫了這篇博文來記錄自我感覺的較簡單的步驟較少的方法去搭建一個springboot web專案,不常寫文可能思路有點混亂,
Code
創建專案
這里使用的IDE是IDEA,選擇軟體左上角File -> New -> Project來創建一個新的專案

選擇Spring Initializr來初始化我們的SpringBoot專案,選擇JDK8之后點擊Next,接下來的點擊Next操作就不做說明了

在如下界面我們設定包名,專案型別選擇Maven專案,語言選擇Java,打包方式選擇Jar,Java版本選擇8

依賴這部分,我們分別選擇Web下的Spring Web,Template Engines下的Thymeleaf(為以后挖坑),SQL下的MyBatis Framework,當然這里也可以創建專案之后手動在POM檔案中寫入,不過這樣更方便一些,

接下來選擇專案的存放路徑,即可完成專案的創建,創建完成專案打開專案之后IDEA右下角會彈出Maven projects need to be imported彈窗,選擇Enable Auto-Import即可,這樣Maven就可以自己下載依賴,
目錄結構
我們打開新建的專案之后大致如下圖所示,.idea檔案夾下存放的是IDEA專案的組態檔,比如compiler.xml 配置了JDK版本,encodings.xml 配置了編碼型別,該檔案夾我們不需要過多了解,.mvn檔案夾下存放的是Maven的配置和相關Jar包,src檔案夾是我們主要編碼的地方,src.main.java路徑下是我們撰寫java代碼的地方,src.main.resources是我們存放靜態資源,頁面以及組態檔的地方,test檔案夾是我們撰寫測驗代碼的地方,.gitignore檔案配置了我們使用git時忽略上傳的檔案,HELP.md是一個幫助檔案,mvnw是一個linux腳本檔案,可以使我們運行指定版本的Maven,mvnw.cmd則是相同功能的windows版本腳本檔案,pom.xml是Maven專案的依賴組態檔,t1.iml是 intellij idea的工程組態檔,里面是當前t1 project的一些配置資訊,

我們主要關注的還是src檔案夾下的檔案,其余不重要的檔案可以隱藏,選中t1 專案,然后點擊這個檔案夾右下角帶三個小藍色方塊的圖示

選擇要隱藏的檔案右鍵選擇Excluded 然后這些檔案夾就會變成橙黃色

點擊Apply回到原來的頁面點擊圖片中右上角的小齒輪,點擊取消Show Excluded Files,這樣想要隱藏的檔案就消失了

測驗啟動
首先我們先來測驗一下SpringBoot框架是否能夠啟動,創建TestController檔案,目錄結構如下

該類的代碼如下
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController // 標注該類為Controller,SpringBoot會自動掃描該類
public class TestController {
@RequestMapping("/test") // 處理請求路徑為/test的請求
public String test(){
return "測驗成功";
}
}
注:自己敲代碼的時候會自動導包,如果是復制上去的話可能不會自動導,需要手動處理,
接下來點擊下圖左側主啟動類的小箭頭或者右上角的箭頭都可以啟動專案

然后觀察控制臺的輸出,很自然的沒有運行成功,出錯了,我們看一下錯誤提示
APPLICATION FAILED TO START
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
大體意思就是沒有配置資料庫驅動,我們也沒用到資料庫啊?為啥要配置資料庫驅動呢?還記得我們之前選擇依賴的時候選擇了mybatis嗎,原因就出在這里,找到pom.xml檔案注釋掉mybatis依賴,重啟專案,
<!-- <dependency>-->
<!-- <groupId>org.mybatis.spring.boot</groupId>-->
<!-- <artifactId>mybatis-spring-boot-starter</artifactId>-->
<!-- <version>2.1.3</version>-->
<!-- </dependency>-->
專案成功啟動控制臺輸出如下

我們可以看到程式啟動在8080埠,在瀏覽器中輸入請求地址即可看到我們想要得到的測驗成功字串

我們百度可以了解到mybatis是一個Java持久層框架,JDBC才是連接資料庫用到的驅動,那為什么我們引入mybatis需要配置資料庫驅動呢?

我們從上面這張圖片可以看到mybatis-spring-boot-starter依賴包含了jdbc依賴,所以引入了mybatis就相當于引入了jdbc,再加上SpringBoot的自動配置是根據是否引入類來進行自動配置的,自然的,引入了jdbc依賴就需要配置資料庫驅動程式(選擇資料庫驅動自然是沒法自動配置的),從如下的報錯也可以得出同樣結論,
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class
連接資料庫
我們使用mysql資料庫,首先創建一個資料庫,我起的名字叫t1并創建了一張表Bear

表內欄位如下

然后隨便添加點資料,這樣我們資料庫就準備好了,
再次回到代碼這邊,首先我們是要配置資料庫的連接資訊,在application.properties里做如下配置
# 資料庫設定
## 資料庫驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 資料庫連接地址
spring.datasource.url=jdbc:mysql://localhost:3306/t1
# 資料庫用戶名
spring.datasource.username=root
# 資料庫密碼
spring.datasource.password=root
其次是匯入JDBC驅動,在pom.xml中添加如下代碼
<!-- mysql jdbc 驅動 https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
因為我安裝的是5.7版本的mysql所以這里我選擇的是5版本的jdbc,如果是8版本的mysql可能就需要選擇8版本的驅動了,驅動程式可以在maven倉庫找到,同時我們要解開之前對mybatis依賴的注釋,
接下來我們要創建一個物體Bear,用來承接Bear表查詢出來的資料,在t1目錄下創建controller的同級目錄entity,再在entity內創建java檔案Bear.java,內容如下
package com.ljsh.t1.entity;
public class Bear {
private String name;
private String type;
private String weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public Bear(String name, String type, String weight) {
this.name = name;
this.type = type;
this.weight = weight;
}
}
一個典型的pojo,下面的getter和setter方法可以在idea編碼頁面右鍵選擇 Generate -> Getter and Setter 自動生成,
再之后是對mybaitis的配置與操作,創建controller目錄同級目錄mapper,在mapper目錄中創建介面檔案TestMapper.java,代碼內容如下
package com.ljsh.t1.mapper;
import com.ljsh.t1.entity.Bear;
import java.util.List;
public interface TestMapper {
List<Bear> getAllBears(); //查詢Bear表所有資料,作為List查出來
}
同樣的在resources目錄下也創建一個mapper檔案夾,mapper檔案夾里創建TestMapper.xml檔案,內容如下
<?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="com.ljsh.t1.mapper.TestMapper">
<select id="getAllBears" resultType="com.ljsh.t1.entity.Bear">
select
*
from Bear
</select>
</mapper>
在T1Applicatin檔案也就是主啟動類中添加一個注解如下
package com.ljsh.t1;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.ljsh.t1.mapper") //掃描mapper介面類
public class T1Application {
public static void main(String[] args) {
SpringApplication.run(T1Application.class, args);
}
}
最后在application.properties中增加一行
# 指向映射xml檔案目錄
mybatis.mapperLocations=classpath:mapper/*.xml
現在的目錄結構如下

通過在主啟動類上配置@MapperScan注解,讓springboot掃描需要實作的Mapper介面檔案,通過組態檔里xml地址的配置,讓Mapper介面和Mapper的xml實作可以對應起來,
最后我們在TestController里修改代碼
package com.ljsh.t1.controller;
import com.ljsh.t1.entity.Bear;
import com.ljsh.t1.mapper.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController // 標注該類為Controller,SpringBoot會自動掃描該類
public class TestController {
@Autowired
TestMapper testMapper; //自動注入
@RequestMapping("/test") // 處理請求路徑為/test的請求
public Object test(){
List<Bear> bears = testMapper.getAllBears();
return bears;
}
}
重新啟動專案訪問http://localhost:8080/test我們會收到從資料庫查詢出來的資料

這時候查看控制臺可能會發現一些警告
Thu Jan 14 22:45:15 CST 2021 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
修改application.properties中的資料庫連接為如下即可消除警告
spring.datasource.url=jdbc:mysql://localhost:3306/t1?useSSL=false
結束語
本來的出發點是以最簡單的方式搭建一個能跑起來的web專案,但是寫完了感徑訓是有點復雜,但有基礎的話還是很好理解的,之后應該還會根據這個demo更新 mvc / 配置 /mybatis 具體的一些細節,也是自己的一次復習,如果有時間的話,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/248863.html
標籤:Java
上一篇:java中String str=""與new String()的區別
下一篇:優雅地創建未定義類PHP物件
