springboot入門一(快速入門)

內容概述

  • Spring概述、快速入門
  • SpringBoot配置
  • SpringBoot整合

一、SpringBoot概述

SpringBoot提供了一種快速使用Spring的方式,基於約定優於配置的思想,可以讓開發人員不必在配置與邏輯業務之間進行思維的切換,全身心的投入到邏輯業務的代碼編寫中,從而大大提高了開發的效率

SpringBoot功能

1自動配置

Spring Boot的自動配置是一個運行時(更準確地說,是應用程序啓動時)的過程,考慮了衆多因素,才決定Spring配置應該用哪個,不該用哪個。該過程是SpringBoot自動完成的。

2起步依賴

起步依賴本質上是一個Maven項目對象模型(Project Object Model,POM),定義了對其他庫的傳遞依賴,這些東西加在一起即支持某項功能。

簡單的說,起步依賴就是將具備某種功能的座標打包到一起,並提供一些默認的功能。

3輔助功能

提供了一些大型項目中常見的非功能性特性,如嵌入式服務器、安全、指標,健康檢測、外部配置等。

注意:Spring Boot 並不是對 Spring 功能上的增強,而是提供了一種快速使用 Spring 的方式。

二、SpringBoot快速入門

需求:搭建SpringBoot工程,定義HelloController.hello()方法,返回”Hello SpringBoot!”。

實現步驟

①創建Maven項目

②導入SpringBoot起步依賴

<!--springboot工程需要繼承的父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
    </parent>

    <dependencies>
        <!--web開發的起步依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

③定義Controller

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return " hello Spring Boot !";
    }
}

④編寫引導類

/**
 * 引導類。 SpringBoot項目的入口
 */
@SpringBootApplication
public class HelloApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class,args);
    }
}

⑤啓動測試
程序執行結果
在這裏插入圖片描述
在這裏插入圖片描述

快速構建SpringBoot工程

在這裏插入圖片描述
在這裏插入圖片描述

在這裏插入圖片描述
創建Controller
在這裏插入圖片描述

程序執行結果:
在這裏插入圖片描述

注意:controller要和啓動類在同一級目錄

SpringBoot起步依賴原理分析

  • 在spring-boot-starter-parent中定義了各種技術的版本信息,組合了一套最優搭配的技術版本。

  • 在各種starter中,定義了完成該功能需要的座標合集,其中大部分版本信息來自於父工程。

  • 我們的工程繼承parent,引入starter後,通過依賴傳遞,就可以簡單方便獲得需要的jar包,並且不會存在版本衝突等問題。

起步依賴原理?(面試題)

  1. springboot中添加的依賴不需要版本(版本的控制)

    我們的工程繼承了parent工程。parent的父工程spring-boot-dependencies,在這個工程中,定義了所有springboot使用的依賴的版本。

  2. springboot不用自己添加依賴

    基於maven的依賴傳遞,當前模塊添加的依賴如果也有依賴,會自動的添加到當前模塊。

  • 在spring-boot-starter-parent中定義了各種技術的版本信息,組合了一套最優搭配的技術版本。
  • 在各種starter中,定義了完成該功能需要的座標合集,其中大部分版本信息來自於父工程。
  • 我們的工程繼承parent,引入starter後,通過依賴傳遞,就可以簡單方便獲得需要的jar包,並且不會存在版本衝突等問題。

SpringBoot配置-配置文件分類

SpringBoot是基於約定的,所以很多配置都有默認值,但如果想使用自己的配置替換默認配置的話,就可以使用application.properties或者application.yml(application.yaml)進行配置。

  1. 默認配置文件名稱:application

  2. 在同一級目錄下優先級爲:properties>yml > yaml

例如:配置內置Tomcat的端口

properties:

server.port=80

yml:

server: 
 port: 80

程序執行結果如下:
在這裏插入圖片描述

SpringBoot配置-yaml基本語法

  • 大小寫敏感
  • 數據值前邊必須有空格,作爲分隔符
  • 使用縮進表示層級關係
  • 縮進時不允許使用Tab鍵,只允許使用空格(各個系統 Tab對應的 空格數目可能不同,導致層次混亂)。
  • 縮進的空格數目不重要,只要相同層級的元素左側對齊即可
  • ‘’#" 表示註釋,從這個字符一直到行尾,都會被解析器忽略。
server: 
	port: 8080  
    address: 127.0.0.1
name: abc

SpringBoot配置-yaml數據格式

對象(map):鍵值對的集合。

person:  
   name: zhangsan
# 行內寫法
person: {name: zhangsan}

數組:一組按次序排列的值

#注意 - 後面也要帶個空格
address:
  - beijing
  - shanghai
# 行內寫法
address: [beijing,shanghai]

純量:單個的、不可再分的值

msg1: 'hello \n world'  # 單引忽略轉義字符
msg2: "hello \n world"  # 雙引識別轉義字符

參數引用

name: lisi 
person:
  name: ${name} # 引用上邊定義的name值

SpringBoot配置-獲取數據

@Value

   #獲取普通配置
   @Value("${name}")
    private String name;
    #獲取對象屬性
    @Value("${person.name}")
    private String name2;
   	#獲取數組
    @Value("${address[0]}")
    private String address1;
  	#獲取純量
    @Value("${msg1}")
    private String msg1;

Evironment

@Autowired
 private Environment env;

System.out.println(env.getProperty("person.name"));

 System.out.println(env.getProperty("address[0]"));

SpringBoot配置-獲取數據_2

@ConfigurationProperties

注意:prefix一定要寫

@Component
@ConfigurationProperties(prefix = "person")
public class Person {

    private String name;
    private int age;
    private String[] address;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String[] getAddress() {
        return address;
    }

    public void setAddress(String[] address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

在這裏插入圖片描述
在這裏插入圖片描述

SpringBoot配置-profile

  1. profile是用來完成不同環境下,配置動態切換功能的

  2. profile配置方式

​ 多profile文件方式:提供多個配置文件,每個代表一種環境。

​ application-dev.properties/yml 開發環境

​ application-test.properties/yml 測試環境

​ application-pro.properties/yml 生產環境

​ yml多文檔方式:

​ 在yml中使用 — 分隔不同配置

  1. profile激活方式
  • 1、配置文件: 在配置文件中配置:spring.profiles.active=dev (properties方式)
    yml方式
    在這裏插入圖片描述

  • 2、 虛擬機參數:在VM options 指定:-Dspring.profiles.active=dev (優先級高於方式1)

  • 3、 命令行參數:java –jar xxx.jar --spring.profiles.active=dev (優先級最高)

SpringBoot配置-項目內部配置文件加載順序

加載順序爲上文的排列順序,高優先級配置的屬性會生效

  • file:./config/:當前項目下的/config目錄下
  • file:./ :當前項目的根目錄
  • classpath:/config/:classpath的/config目錄
  • classpath:/ :classpath的根目錄

SpringBoot配置-項目外部配置加載順序

外部配置文件的使用是爲了與內部文件的配合

1.命令行

java -jar app.jar --name="Spring“ --server.port=9000

注意命令行打開springboot項目失敗的問題

啓動SPRINGBOOT的可執行JAR 報錯:TARGET\SPRING-BOOT-HELLO-1.0-SNAPSHOT.JAR中沒有主清單屬性
打包成功,但是在執行時報錯,沒有主清單屬性

解決:在pom文件中增加下面的代碼

<build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
</plugins>
</build>

在這裏插入圖片描述

2.指定配置文件位置

 java -jar myproject.jar --spring.config.location=e://application.properties

3.外部不帶profile的properties文件

    classpath:/config/application.properties
    classpath:/application.properties

https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config

在這裏插入圖片描述

SpringBoot整合Junit

  1. 搭建SpringBoot工程

  2. 引入starter-test起步依賴

<!--springboot工程需要繼承的父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
    </parent>


 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  1. 編寫測試類
    啓動類:
package cn.kinggm520;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootJunitApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootJunitApplication.class, args);
    }

}

模擬服務類:

package cn.kinggm520;

import org.springframework.stereotype.Service;

@Service
public class UserService {

    public void show(){
        System.out.println("show....");
    }
}

測試類

import cn.kinggm520.SpringbootJunitApplication;
import cn.kinggm520.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 測試類
 */

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJunitApplication.class )

public class TestAAA {

    @Autowired
    private UserService userService;
    @Test
    public void test() {
        System.out.println(111);
        userService.show();
    }

}


在這裏插入圖片描述

4.測試結果:
在這裏插入圖片描述

注意:如果測試類的包結構和springboot啓動類的包結構相同 那麼測試類裏面的

@SpringBootTest(classes = SpringbootJunitApplication.class )註解 classes 就不用指定了

SpringBoot整合mybatis

①搭建SpringBoot工程

②引入mybatis起步依賴,添加mysql驅動

<!--springboot工程需要繼承的父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
    </parent>


<dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <!--<scope>runtime</scope>-->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

③編寫DataSource和MyBatis相關配置

application.yml

# datasource
spring:
  datasource:
    url: jdbc:mysql:///db_springboot?serverTimezone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver


# mybatis
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml # mapper映射文件路徑
  type-aliases-package: cn.kinggm520.domain

  # config-location:  # 指定mybatis的核心配置文件

④定義表和實體類

public class User {
    private int id;
    private String username;
    private String password;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

在這裏插入圖片描述

⑤編寫dao和mapper文件/純註解開發

編寫dao

@Mapper
@Repository
public interface UserXmlMapper {

    public List<User> findAll();
}

mapper.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="cn.kinggm520.mapper.UserXmlMapper">
    <select id="findAll" resultType="user">
        select * from t_user
    </select>
</mapper>

純註解開發

@Mapper
@Repository
public interface UserMapper {

    @Select("select * from t_user")
    public List<User> findAll();
}

⑥測試

import cn.kinggm520.SpringBootAndMybatisApplication;
import cn.kinggm520.domain.User;
import cn.kinggm520.mapper.UserMapper;
import cn.kinggm520.mapper.UserXmlMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootAndMybatisApplication.class)
public class TestMybatis {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserXmlMapper userXmlMapper;

    @Test
    public void testMybatis(){
        List<User> list = userMapper.findAll();
        System.out.println(list);

        List<User> all = userXmlMapper.findAll();
        System.out.println(all);
    }
}

SpringBoot整合redis

①搭建SpringBoot工程

②引入redis起步依賴

   <!--springboot工程需要繼承的父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
    </parent>

  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

③配置redis相關屬性

spring:
  redis:
    host: 127.0.0.1 # redis的主機ip
    port: 6379

④注入RedisTemplate模板

@Autowired
    private RedisTemplate redisTemplate;

⑤編寫測試方法,測試

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRedisApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testSet() {
        //存入數據
        redisTemplate.boundValueOps("name").set("zhangsan");
    }

    @Test
    public void testGet() {
        //獲取數據
        Object name = redisTemplate.boundValueOps("name").get();
        System.out.println(name);
    }

}

注意 Springboot的啓動類要放在 定義的包結構目錄下 不能放在默認的java目錄下否則報錯** WARNING ** : Your ApplicationContext is unlikely to start due to a @ComponentScan of the default package.

在這裏插入圖片描述
解決辦法 直接在java目錄下新建一個包把啓動類放進去即可

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