SpringBoot基础

1.SpringBoot概述

SpringBoot介绍

SpringBoot提供了一种快速使用Spring的方式基于约定优于配置的思想,可以让开发人员不必在配置与逻辑业务之间进行思维的切换,全身心的投入到逻辑业务的代码编写中,从而人大提高了开发的效率,一定程度上缩短了项目周期

2014年4月,Spring Boot 1.0.0发布。是Spring的顶级项目之一(https://spring.io)

Spring缺点

配置繁琐

虽然Spring的组件代码是轻量级的,但它的配置却是重量级的一开始,Spring用XML配置,而且是很多XML配置Spring 2.5引入了基于注解的组件扫描,这消除了大量针对应用程序自身组件的显式XML配置Spring 3.0引入了基于Java的配置,这是一种类型安全的可重构配置方式,可以代替XML

所有这些配置都代表了开发时的损耗因为在思考Spring特性配置和解决业务问题之间需要进行思维切换,所以编写配置挤占了编写应用程序逻辑的时间。和所有框架一样,Spring实用,但它要求的回报也不少

依赖繁琐 

项目的依赖管理也是一件耗时耗力的事情。在环境搭建时,需要分析要导入哪些库的坐标,而且还需要分析导入与之有依赖关系的其它库的坐标。一旦选错了依赖的版本,随之而来的不兼容问题就会严重阻碍项目的开发进度

SpringBoot功能

1.自动配置

Spring Boot的自动配置是一个运行时(更准确地说,是应用程序启动时)的过程,考虑了众多因素,才决定Spring配置应该用哪个,不该用哪个。该过程是SpringBoot自动完成的

2.起步依赖

起步依赖本质上是一个Maven项目对象模型(Project Object Model,POM),定义了对其他库的传递依赖,这些东西加在一起即支持某项功能。

简单的说,起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认的功能

3.辅助功能

提供了一些大型项目中常见的非功能性特性,如嵌入式服务器、安全、指标,健康检测、外部配置等。

注意:Spring Boot 并不是对 Spring 功能上的增强,而是提供了一种快速使用 Spring 的方式

2.快速入门

需求

搭建SpringBoot工程,定义HelloController。hello()方法,返回"Hello SpringBoot"

实现步骤

1.创建Maven项目

2.导入SpringBoot起步依赖

3.定义Controller

4.编写引导类

5.启动测试

<?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>

    <groupId>com</groupId>
    <artifactId>boot-helloword</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <!--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>
</project>
package com.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String hello(){
        return "hello Spring Boot!";
    }
}
package com;

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

/*
    引导类:SpringBoot项目的入口
*/
@SpringBootApplication
public class HelloApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class,args);
    }
}

注:

SpringBoot在创建项目时,使用jar的打包方式

SpringBoot的引导类,是项目入口,运行main方法就可以启动项目

使用SpringBoot和Spring构建的项目,业务代码编写方式完全一样

3.快速构建SpringBoot工程

Spring提供快速创建模版:https://start.spring.io/

springboot在idea更新后只能用java17以上版本用不了jdk8

那就是不要用官方提供的 Spring Initializr 来初始化项目了,我们可以使用阿里云提供的脚手架镜像

在 IDEA 里更改 Server URL 即可:https://start.aliyun.com/

4.SpringBoot起步依赖原理分析 

在spring-boot-starter-parent中定义了各种技术的版本信息,组合了一套最优搭配的技术版本

在各种starter中,定义了完成该功能需要的坐标合集,其中大部分版本信息来自于父工程

我们的工程继承parent,引入starter后,通过依赖传递,就可以简单方便获得需要的jar包,并且不会存在版本冲突等问题

5.配置文件分类

SpringBoot是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以使用application.properties或者application.yml(application.yaml)进行配置。

默认配置文件名称:application

在同一级目录下优先级为:properties>yml > yaml

例如:配置内置Tomcat的端口

properties:

server.port=8080

yml:

server: 
  port: 8080

6.yaml基本语法

YAML全称是YAML Ain't Markup Language。YAML是一种直观的能够被电脑识别的的数据序列化格式,并且容易被人类阅读,容易和脚本语言交互的,可以被支持YAML库的不同的编程语言程序导入,比如:C/C++,Ruby,Python,Java,Perl,C#,PHP等。YML文件是以数据为核心的,比传统的xml方式更加简洁

YAML文件的扩展名可以使用.yml或者.yaml

简洁,以数据为核心 

基本语法

大小写敏感

数据值前边必须有空格,作为分隔符

使用缩进表示层级关系

缩进时不允许使用Tab键,只允许使用空格(各个系统 Tab对应的 空格数目可能不同,导致层次混乱)

缩进的空格数目不重要,只要相同层级的元素左侧对齐即可

‘’#" 表示注释,从这个字符一直到行尾,都会被解析器忽略

7.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值

8.读取配置内容(获取数据) 

@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;

    @RequestMapping("/hello2")
    public String hello2() {
        System.out.println(env.getProperty("person.name"));
        System.out.println(env.getProperty("address[0]"));
        return "hello Spring Boot";
    }

使用 @Component + @ConfigurationProperties组合注解读取对象的属性

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private int age;
    private String[] address;

    //Getter and Setter
    //toString
}

注意:prefix一定要写

package com.boothelloword2.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @Value("${name}")
    private String name;

    @Value("${person.name}")
    private String name2;

    @Value("${person.age}")
    private int age;

    @Value("${address[0]}")
    private String address1;

    @Value("${msg1}")
    private String msg1;

    @Value("${msg2}")
    private String msg2;

    @Autowired
    private Environment env;

    @RequestMapping("/hello2")
    public String hello2() {
        System.out.println(name);
        System.out.println(name2);
        System.out.println(age);
        System.out.println(address1);
        System.out.println(msg1);
        System.out.println(msg2);

        System.out.println("----------------------");

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

        System.out.println("-------------------");


        return "hello Spring Boot 222!";
    }

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

9.profile

我们在开发Spring Boot应用时,通常同一套程序会被安装到不同环境,比如:开发、测试、生产等其中数据库地址、服务器端口等等配置都不同,如果每次打包时,都要修改配置文件,那么非常麻烦。profile功能就是来进行动态配置切换的

profile配置方式

​多profile文件方式:提供多个配置文件,每个代表一种环境。

application-dev.properties/yml 开发环境

application-test.properties/yml 测试环境

application-pro.properties/yml 生产环境

yml多文档方式:在yml中使用 --- 分隔不同配置(固定3个-)

profile激活方式

配置文件: 再配置文件中配置:spring.profiles.active=dev

虚拟机参数:在VM options 指定:-Dspring.profiles.active=dev

命令行参数:java –jar xxx.jar --spring.profiles.active=dev

profile是用来完成不同环境下,配置动态切换功能的

10.项目内部配置文件加载顺序

SpringBoot程序启动时,会从以下位置加载配置文件

1.file:./config/:当前项目下的/config目录下

2.file:./ :当前项目的根目录

3.classpath:/config/:classpath的/config目录

4.classpath:/ :classpath的根目录

加载顺序为上文的排列顺序,高优先级配置的属性会生效

11项目外部配置加载顺序

优先级从高到低

1.命令行参数(所以我们java -jar启动时指定的参数优先级最高)

所有的配置都可以在命令行上进行指定;

多个配置用空格分开; --配置项=值

--server.port=8087 --server.context-path=/abc

2.Java系统属性(System.getProperties())

Spring启动的时候,默认会把系统的很多属性都默认加载进来

注:因此你自定义key的时候,应该去避免和系统自带的key重名,否则不起作用 

3.操作系统环境变量(比如操作系统的username等等)

4.RandomValuePropertySource配置的random.*属性值

5.jar包外部的application-{profile}.properties配置文件

6.jar包内部的application-{profile}.properties配置文件

7.jar包外部的application.properties配置文件(此级别在测试环境经常使用。比如就在jar包同级目录放置一个配置文件,就内覆盖jar包内部所有的配置文件了)

8.jar包内部的application.properties配置文件

注:由jar包外向jar包内进行寻找,优先加载待profile的,再加载不带profile的

9.@Configuration注解类上的@PropertySource(手动指定导入外部配置文件)

10.通过SpringApplication.setDefaultProperties指定的默认属性,自己程序代码里设置,优先级最低

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

12SpringBoot整合Junit

1.搭建SpringBoot工程

2.引入starter-test起步依赖

3.编写测试类

4.添加测试相关注解

    @RunWith(SpringRunner.class)

    @SpringBootTest(classes = 启动类.class)

5.编写测试方法

<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>
package com;

import org.springframework.stereotype.Service;

@Service
public class UserService {
    public void add(){
        System.out.println("add...");
    }
}
package com.test;

import com.BootTestApplication;
import com.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;

/*
* userService的测试类
* */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = BootTestApplication.class)
public class UserServiceTest {
    @Autowired
    private UserService userService;
    @Test
    public void testAdd(){
        userService.add();
    }
}

注:当测试类的包与主包的子包相同则可以不写@SpringBootTest后的东西

13.SpringBoot整合Redis

1.搭建SpringBoot工程

2.引入redis起步依赖

3.配置redis相关属性

4.注入RedisTemplate模板

5.编写测试方法,测试

<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>
spring:
  redis:
    host: 127.0.0.1 # redis的主机ip
    port: 6379
package com.bootredis;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
class BootRedisApplicationTests {

    @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);
    }

}

14.SpringBoot整合Mybatis 

1.搭建SpringBoot工程

2.引入mybatis起步依赖,添加mysql驱动

3.编写DataSource和Mybatis相关配置

4.定义表和实体类

5.编写dao和mapper文件/纯注解开发

6.测试

<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>

创建数据库

DROP TABLE IF EXISTS `t_user`;

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `password` varchar(32) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

insert  into `t_user`(`id`,`username`,`password`) values (1,'zhangsan','123'),(2,'lisi','234');


application.yml

#datasource
spring:
  datasource:
    url: jdbc:mysql:///spring_db?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: com.bootmybatis.domain
  #config-location: #指定mybatis的核心配置文件
package com.bootmybatis.domain;

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 + ''' +
                '}';
    }
}
package com.bootmybatis.mapper;

import com.bootmybatis.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserXmlMapper {
    public List<User> findAll();
}
<?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.bootmybatis.mapper.UserXmlMapper">
    <select id="findAll" resultType="user">
        select * from t_user
    </select>
</mapper>

纯注解开发

package com.bootmybatis.mapper;

import com.bootmybatis.domain.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;
@Mapper
public interface UserMapper {
    @Select("select * from t_user")
    public List<User> findAll();
}

测试

package com.bootmybatis;

import com.bootmybatis.domain.User;
import com.bootmybatis.mapper.UserMapper;
import com.bootmybatis.mapper.UserXmlMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class BootMybatisApplicationTests {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserXmlMapper userXmlMapper;
    @Test
    public void testFindAll(){
        List<User> list = userMapper.findAll();
        System.out.println(list);
    }

    @Test
    public void testFindAll2(){
        List<User> list = userXmlMapper.findAll();
        System.out.println(list);
    }
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>