從簡入深的使用SpringBoot搭建一個Web項目,同時也包括一些小的問題。第一篇博文是以較爲簡單的方式完成一個能夠鏈接數據庫的Springboot web程序。以前本身學習的時候看網上的教程老是感受有點太大,我只是想最簡單的搭建一個能夠運行的項目,以後再去深究細節。每一個教程的配置還都不同,讓我不知所措,因此我就寫了這篇博文來記錄自我感受的較簡單的步驟較少的方法去搭建一個springboot web項目,不常寫文可能思路有點混亂。java
這裏使用的IDE是IDEA,選擇軟件左上角File -> New -> Project來建立一個新的項目
mysql
選擇Spring Initializr來初始化咱們的SpringBoot項目,選擇JDK8以後點擊Next,接下來的點擊Next操做就不作說明了
linux
在以下界面咱們設置包名,項目類型選擇Maven項目,語言選擇Java,打包方式選擇Jar,Java版本選擇8
git
依賴這部分,咱們分別選擇Web下的Spring Web,Template Engines下的Thymeleaf(爲之後挖坑),SQL下的MyBatis Framework,固然這裏也能夠建立項目以後手動在POM文件中寫入,不過這樣更方便一些。
web
接下來選擇項目的存放路徑,便可完成項目的建立,建立完成項目打開項目以後IDEA右下角會彈出Maven projects need to be imported彈窗,選擇Enable Auto-Import便可,這樣Maven就能夠本身下載依賴。spring
咱們打開新建的項目以後大體以下圖所示。.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的一些配置信息。
sql
咱們主要關注的仍是src文件夾下的文件,其他不重要的文件能夠隱藏,選中t1 項目,而後點擊這個文件夾右下角帶三個小藍色方塊的圖標
數據庫
選擇要隱藏的文件右鍵選擇Excluded 而後這些文件夾就會變成橙黃色
windows
點擊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 具體的一些細節,也是本身的一次複習,若是有時間的話。