人見人愛的Spring Boot經典入門教程,誰看了都說好

前言

Springboot是現在學習Java開發必備的一個技術點。講真,這是一個非常簡單的東西,只要花一點時間都可以非常愉快的把它用起來。但是現在教程一般都是兩種,一種是使用idea直接創建就開始用,導致感覺懂了,但是又有很多細節流失。另一種是先講大篇原理,半天不入門,讓很多初學者摸不到頭腦。 所以我想從使用層面入手,但是不丟失細節的方式來帶大家入門。

一.認識SpringBoot

  • 爲簡化Spring項目配置而生
  • 使用maven的方式對Spring應用開發進行進一步封裝和簡化
  • 爲了簡化spring應用搭建,開發,部署,監控的開發工具
  • 官網:spring.io/projects/sp…

二.Maven的父子項目認識

本節與SpringBoot無關,已經瞭解Maven父子關係的同學可以忽略本章

咱們剛纔說了,SpringBoot是使用maven(注:也可以使用Gradle)的方式對Spring應用開發進行進一步的封裝和簡化。所以咱們在學習SpringBoot前需要學習Maven,而在練習前咱們會創建多個練習demo,因此,在這裏需要先進行Maven父子模塊講解(已經瞭解Maven父子模塊可以忽略本章)

  • idea只能創建一個項目,所以咱們會以模塊的方式來進行項目的創建
  • 咱們會先創建一個父項目,然後在裏面創建多個子模塊

2.1 創建一個普通Maven項目

 

 

  • 開發工具使用idea

2.1.1 創建普通的maven項目(父項目)

  • 取名springboot-parent

 

 

 

 

 

 

 

2.1.2 創建的模塊項目

  • 取名springboot-hello-01

 

 

 

 

 

 

 

 

2.2 父子模塊分析

主要是分析兩個pom.xml中的內容

2.2.1 父模塊pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--組id-->
    <groupId>cn.itsource</groupId>
    <!--模塊名稱-->
    <artifactId>springboot-parent</artifactId>
    <!--
        packaging
            jar === 當前項目打成jar包
            war === 當前項目打成war包
            pom === 當前項目不寫java代碼,權代表用於管理jar包
            maven-plugin === 當前項目用於開發插件使用(暫時不用管)
    -->
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>

    <!--父項目中管理的所有子項目模塊-->
    <modules>
        <!--管理的子項目模塊,注意名稱和子模塊名稱保持一致-->
        <module>springboot-hello-01</module>
    </modules>


</project>
複製代碼

2.2.2 子模塊pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <!--
        當前子模塊的pom.xml中沒有聲音自己的版本與主id
        通過parent 引入父模塊中的內容(這裏是繼承關係)
    -->
    <parent>
        <artifactId>springboot-parent</artifactId>
        <groupId>cn.itsource</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <!--子模塊的名稱-->
    <artifactId>springboot-hello-01</artifactId>
</project>
複製代碼

三.Hello,SpringBoot

3.1 繼承springboot的父依賴

  • springboot爲咱們準備好了相關依賴jar包(下面代碼直接拷貝使用即可)
  • pom.xml是單繼承的結構,所以我們在父pom.xml中繼承父依賴
  • 父依賴中已經聲明瞭很多現在可用的jar包(大家可看源碼分析)
  • dependencyManagement:只聲明 不引用
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
</parent>
複製代碼

3.2 子pom.xml中添加依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
複製代碼

3.3 創建controller

@Controller
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping("/01")
    @ResponseBody
    public String hello01(){
        return "hello springboot";
    }
}
複製代碼

3.4 創建啓動類

特別注意:啓動類必需在外層

//申明我當前是一個SpringBoot的應用
@SpringBootApplication
public class ApplicationConfig {

    public static void main(String[] args) {
        // 注:這裏傳入的字段碼對象,必需是聲明瞭@SpringBootApplication的類
        //啓動SpringBoot程序
        SpringApplication.run(ApplicationConfig.class);
    }
}

複製代碼

3.5 注意事項(疑問)

  1. 爲什麼要繼承spring-boot-starter-parent 父項目準備了很多應用的插件與jar包,子項目可以直接引用即可(方便開發)
  2. 當前項目引入 spring-boot-starter-web是什麼意思? 在引入後就會導入spring運行web項目的所有jar包(如spring,日誌,mvc包等等) springboot有組合包的概念,專門用於簡化maven的導包 springboot提供包的格式: spring-boot-starter-xxx
  3. 居然一個主方法啓動了tomcat spring-boot-starter-web內嵌了一個tomcat插件
  4. 爲什麼主方法運行後,應用程序就啓動了 初始化運行程序中的所有bean對象(只有掃描它所有的包及其子包的java對象) 自動裝配springmvc的相關代碼與配置(有默認的配置,我們以後可以修改) 初始化spring容器 把當前應用打成一個jar包放到tomcat中運行

四.SpringBoot三種運行方式

4.1 直接在工具中運行main方法

最簡單,咱們平時開發時也就這樣直接運行

 

 

4.2 插件運行

  1. 引入插件
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
複製代碼
  1. 運行項目

4.3 打包運行

注:打包運行必需要引入插件 咱們以後開發項目放到服務器中運行,就可以使用這種方式

 

 

 

 

  • 當前位置打開cmd,並且輸入java -jar springboot-hello-01-1.0-SNAPSHOT.jar

 

 

五.熱部署方案

  • 在pom.xml中加上熱部署插件(代碼如下)
  • 修改代碼後按 ctrl+f9 進行編譯
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
   <scope>true</scope>
</dependency>	
複製代碼

六.SpringBoot配置文件

6.1 springboot配置文件認識

  • 默認配置文件會在resources中
  • 配置文件有兩種(我們任選一種即可) application.properties application.yml

6.2 application.properties

properties的配置咱們以前都已經學過,這裏簡單看一下端口修改的配置即可

server.port=80
server.servlet.path=/haha
複製代碼

 

 

6.3 application.yml的配置

yml是一種更加優雅的配置方式(有層次結構),之後咱們都直接使用yml的方式來做配置

6.3.1 基本用法

  • 以空格的縮進來控制層級關係;只要是左對齊的一列數據,都是同一個層級的
  • k:(空格)v:表示一對鍵值對(空格必須有)
  • 屬性和值也是大小寫敏感
server:
  port: 8088
  servlet:
    path: /haha
複製代碼

6.3.2 字符串的字面量

  • 字符串不需要加引號
  • 雙引號不會對串中轉義字符進行轉義 name: "zhangsan \n lisi":輸出;zhangsan 換行 lisi
  • 單引號轉義特殊字符 name: "zhangsan \n lisi":輸出;zhangsan \n lisi

注:以後配置文件中可能還會寫數組,集合等,後面的課程涉及到會單獨講解,大家也可以自行在網上進行查找

6.4 多環境支持方案

咱們以後可能會遇到一個項目多個環境(開發,測試,上線等),爲不同的環境會寫一些不同的配置,那麼就需要咱們做相應的環境之間的切換

6.4.1 多文檔塊模式

  • 使用三個框(---)來區分
  • 可調用不同的方式
# 確定哪一個模塊爲活動模塊
spring:
  profiles:
    active: pro

---
#開發模塊
server:
  port: 8088
spring:
  profiles: dev

---
#測試模塊
server:
  port: 8089
spring:
  profiles: test

---
#在線模塊
server:
  port: 8099
spring:
  profiles: pro

複製代碼

6.4.2 多profile文件模式

  • 創建多個yml文件,注意名稱都是 applicaton-xxx.yml命名(如下截圖)

 

 

七.SpringBoot的測試功能

  1. 在咱們父模塊下新建一個子模塊 springboot-test
  2. 引入springboot的測試starter
  3. SpringBoot的啓動類
  4. 準備一個bean讓Spring管理
  5. 完成測試(看是否可以注入使用這個bean)

7.1 最近創建好的結構

 

 

7.2 引入測試依賴(starter)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>
複製代碼

7.3 準備啓動類

@SpringBootApplication //聲明這是一個springboot應用
public class ApplicationConfig {
    public static void main(String[] args) {
        SpringApplication.run(ApplicationConfig.class,args);
    }
}
複製代碼

7.4 準備一個MyBean讓Spring管理

//創建一個bean
@Component
public class MyBean {
}
複製代碼

7.5 功能測試

@RunWith(SpringRunner.class)
//代表這是一個SpringBoot的測試
// classes對應的類必需是經過SpringBootApplication修飾的類
@SpringBootTest(classes=ApplicationConfig.class)
public class MyBeanTest {
    @Autowired
    private MyBean myBean;

    @Test
    public void test01(){
        System.out.println(myBean);
    }
}

複製代碼

七.RestController註解方式

  • 在大量返回json的Controller中使用(以後用得比較多)
  • RestController是一個組合註解 它等於 (@Controller+@ResponseBody)

咱們創建一個新的模塊進行測試,下面爲核心代碼(基礎代碼此處省略)

@RestController
@RequestMapping("/json")
public class JsonController {


    //返回普通數據
    @RequestMapping("/01")
    public String json01(){
        return "hello json";
    }
    //返回對象
    @RequestMapping("/02")
    public Employee json02(){
        return new Employee(1L,"小春風");
    }
    //返回集合
    @RequestMapping("/03")
    public List<Employee> json03(){
        return Arrays.asList(
                new Employee(1L,"令狐兄"),
                new Employee(2L,"不羣兄"),
                new Employee(3L,"我行兄")
        );
    }

    //返回map
    @RequestMapping("/04")
    public Map json04(){
       Map map = new HashMap();
       map.put("name","小飛俠");
       map.put("age",24);
       map.put("sex",false);
       return map;
    }

}
複製代碼

八.Thymeleaf

  • Thymeleaf是一個模板技術 其它的模板技術:freemarker,velocity,jsp等 jsp現在用得很少,因爲它必需依賴servlet容器才能運行,並且編譯的效率低下
  • springboot推薦使用Thymeleaf
  • 詳細語法:fanlychie.github.io/post/thymel…

 

 

8.1 引入thymeleaf的支持包

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--引入thymeleaf的支持-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencies>
複製代碼

8.2 完成thymeleaf的配置

  • 該步驟可以省略,默認前綴classpath:/templates/,後綴.html
spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
複製代碼

8.3 controller完成跳轉傳參

@Controller
public class HelloController {
    @RequestMapping("/hello")
    public String index(Model model){
        model.addAttribute("msg","hello,Springboot");
        return "index";
    }
}
複製代碼

8.4 頁面展示

注:加上xmlns:th="http://www.thymeleaf.org"則會支持thymeleaf的提示

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
        <!--使用語法th:text 可以設置裏面的文本內容 -->
        <div th:text="${msg}">你好啊!兄弟!!!</div>
</body>
</html>
複製代碼

九.框架集成

注: 練習前先準備相應的數據庫與表數據

9.1 導包

導入:數據庫驅動包,springboot與jdbc集成包,mybatis與springboot集成包,springboot的web支持包

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--數據庫驅動包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--springboot與jdbc集成包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!--mybatis提供的與springboot集成包  -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
    </dependencies>
複製代碼

9.2 準備代碼結構

 

 

9.3 yml配置文件

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql:///mytest
    driver-class-name: com.mysql.jdbc.Driver
##mybatis的配置
mybatis:
  # 掃描相應的映射文件
  mapper-locations: classpath:cn/itsource/mapper/*.xml
  # 該包下的對象取別名
  type-aliases-package: cn.itsource.domain
##日誌級別的打印(需要看日誌的可以直接拷備使用:特別注意它的層級)
logging:
  level:
    cn:
      itsource: trace
  root: error
複製代碼

9.4 進行mapper接口的掃描

@SpringBootApplication
//進行相應的映射接口掃描
@MapperScan("cn.itsource.mapper")
public class ApplicationConfig {

    public static void main(String[] args) {
        SpringApplication.run(ApplicationConfig.class);
    }
}
複製代碼

9.4 mapper層功能

  1. mapper的接口功能
public interface UserMapper {
    List<User> findAll();
    void save(User user);
}
複製代碼
  1. mapper的xml文件(注:寫在resource中對應的位置)
<?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="cn.itsource.mapper.UserMapper">

    <select id="findAll"  resultType="User">
        select * from user
    </select>

    <insert id="save" parameterType="User">
        insert into user (username) values (#{username})
    </insert>
</mapper>
複製代碼
  1. 完成功能測試
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationConfig.class)
public class UserMapperTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void mytest(){
        userMapper.findAll().forEach(user -> {
            System.out.println(user);
        });
    }
}
複製代碼

9.5 service層功能

注:Springboot已經集成事務,咱們可以直接使用

1.IUserService代碼

public interface IUserService {
    List<User> findAll();
    void save(User user);
}
複製代碼

2.UserServiceImpl功能實現

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper mapper;

    @Override
    public List<User> findAll() {
        return mapper.findAll();
    }

    @Override
    @Transactional
    public void save(User user) {
        mapper.save(user);
        int i = 1/0;
    }
}
複製代碼

3.測試

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ApplicationConfig.class)
public class UserServiceTest {
    @Autowired
    private IUserService userService;
    @Test
    public void save(){
        User user = new User();
        user.setUsername("虎子xx");
        userService.save(user);
    }
    @Test
    public void findAll(){
        userService.findAll().forEach(user -> {
            System.out.println(user);
        });
    }
}
複製代碼

9.6 controller層功能

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/findAll")
    public List<User> findAll(){
        return userService.findAll();
    }
}
複製代碼

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章