Springboot2.3学习整合

文章由b站拓新教育springboot视频课程整理而成,可作为笔记参考。

1 Spring Boot 基础篇

1.1 Spring Boot 简介

1.1.1 、SpringBoot主要特性

  • 1、SpringBoot Starter:他将常用的依赖分组进行了整合,将其合并到一个依赖中,这样就可以一次性添加到项目的Maven或Gradle构建中;

  • 2、使编码变得简单,SpringBoot采用 JavaConfig的方式对Spring进行配置,并且提供了大量的注解,极大的提高了工作效率。

  • 3、自动配置:SpringBoot的自动配置特性利用了Spring对条件化配置的支持,合理地推测应用所需的bean并自动化配置他们;

  • 4、使部署变得简单,SpringBoot内置了三种Servlet容器,Tomcat,Jetty,undertow.我们只需要一个Java的运行环境就可以跑SpringBoot的项目了,SpringBoot的项目可以打成一个jar包。

  • 5、现在流行微服务与分布式系统,springboot就是一个非常好的微服务开发框架,你可以使用它快速的搭建起一个系统。同时,你也可以使用spring cloud(Spring Cloud是一个基于Spring Boot实现的云应用开发工具)来搭建一个分布式的架构。

1.1.2 springboot缺点

  • 1.将现有或传统的Spring Framework项目转换为Spring Boot应用程序是一个非常困难和耗时的过程。它仅适用于全新Spring项目。
  • 2.使用简单,学习成本高,精通难。

1.2 环境准备

  • jdk1.8:Spring Boot 推荐jdk1.8及以上;
  • maven3.x:maven 3.3以上版本;
    I- ntelliJIDEA2019,不要使用2017
  • SpringBoot 2.3.0.RELEASE
    1.2.1 MAVEN设置
    1.配置阿里云镜像
<mirror>  
	    <id>nexus-aliyun</id>  
	    <mirrorOf>central</mirrorOf>    
	    <name>Nexus aliyun</name>  
	    <url>http://maven.aliyun.com/nexus/content/groups/public</url>  
    </mirror>

2.给maven 的settings.xml配置文件的profiles标签添加

<profile>
			<id>jdk-1.8</id>
			<activation>
			     <activeByDefault>true</activeByDefault>
					 <jdk>1.8</jdk>
			</activation>
			<properties>
			     <maven.compiler.source>1.8</maven.compiler.source>
			     <maven.compiler.target>1.8</maven.compiler.target>
			     <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
			</properties>
		</profile>

1.3 Spring Boot HelloWorld

1.3.1 创建一个maven父工程spring-boot-lession(pom)
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>

    <groupId>org.example</groupId>
    <artifactId>spring-boot-lession</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>springboot-first</module>
    </modules>
    <packaging>pom</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
</project>

1.3.2 在父工程下创建springboot-first(jar)
在这里插入图片描述

1.3.3 创建测试Controller

@RestController
public class TestController {

    @RequestMapping("hello")
    public String show(){
        return "hello world";
    }
}

1.3.4 创建一个springboot启动类

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

1.3.5 在父工程spring-boot-lession中加入构建依赖

 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
 </build>

我们可以把springboot工程打成可执行的jar

mvn -f springboot-first clean package

打完jar包后,我们切入到对应的jar包里面执行

在这里插入图片描述
在这里插入图片描述
== ctrl+c 推出运行 ==

1.4 默认扫描器basepackage

源码解析
@AutoConfigurationPackage
自动配置包负责basepackge的注册
@AutoConfigurationPackage内部使用@Import来做bean的定义的注册
在这里插入图片描述
让我们进入AutoConfigurationPackages.Registrar,通过register的调用来注册basepackage的bean定义的
在这里插入图片描述
进入到PackageImports,获得basepackge设置给packageNames
在这里插入图片描述
回到上一层进入到register,创建bean的定义并且把packageNames设置给bean定义
然后把bean定义的做注册。
在这里插入图片描述

2 热部署

  • 在实际开发过程中,每次修改代码就得将项目重启,重新部署,对于一些大型应用来说,重启时间需要花费大量的时间成本。对于一个后端开发者来说,重启过程确实很难受啊。在 Java 开发领域,热部署一直是一个难以解决的问题,目前的 Java 虚拟机只能实现方法体的修改热部署,对于整个类的结构修改,仍然需要重启虚拟机,对类重新加载才能完成更新操作。下面我们就看看对于简单的类修改的热部署怎么实现。

2.1 原理

  • 深层原理是使用了两个ClassLoader,一个Classloader加载那些不会改变的类(第三方Jar包),另一个ClassLoader加载会更改的类,称为restart ClassLoader,这样在有代码更改的时候,原来的restart ClassLoader 被丢弃,重新创建一个restart ClassLoader,由于需要加载的类相比较少,所以实现了较快的重启时间。

2.2 devtools工具包

  • devtools会监听classpath下的文件变动,并且会立即重启应用(发生在保存时机),
    java类文件热部署(类文件修改后不会立即生效),实现对属性文件的热部署。
    devtools可以实现页面热部署(页面修改后会立即生效,这个可以直接在application.properties文件中配置spring.thymeleaf.cache=false来实现,后面讲到)。

依赖包:

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

2.3 idea的工具设置

  • 当我们修改了类文件后,idea不会自动编译,需要通过ctrl+F9来触发,
  • 如果想要自动生效得修改idea设置,该功能按着个人的喜好来设置,修改类后,当我们窗口切换时候可以看到热部署的发生
    (1)File-Settings-Compiler-Build Project automatically
    (2)ctrl + shift + alt + / ,选择Registry,勾上 Compiler autoMake allow when app running
    在这里插入图片描述

在这里插入图片描述

2.4 热部署的排除

  • 默认情况下,/META-INF/maven,/META-INF/resources,/resources,/static,/templates,/public这些文件夹下的文件修改不会使应用重启,但是会重新加载(devtools内嵌了一个LiveReload server,当资源发生改变时,浏览器刷新)。
  • 1.我们在resources/static目录下创建tx.js文件每次发生修改后的并不重启,而是采用livereload的方式。
  • 2.同时我们可以根据自己的意愿来设置想要排除的资源
spring.devtools.restart.exclude=static/**,public/**

3 boot的属性配置文件

3.1 配置文件位置

  • springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件
    –file:./config/
    –file:./ 项目的跟路径,如果当前的项目有父工程,配置文件要放在父工程 的根路径
    –classpath:/config/
    –classpath:/
    优先级由高到底,高优先级的配置会覆盖低优先级的配置;
    SpringBoot会从这四个位置全部加载主配置文件;互补配置;

  • 如果我们的配置文件名字不叫application.properties或者application.yml,可以通过以下参数来指定配置文件的名字,myproject是配置文件名

$ java -jar myproject.jar --spring.config.name=myproject

我们同时也可以指定其他位置的配置文件来生效

$ java -jar myproject.jar -- spring.config.location=classpath:/default.properties,classpath:/override.properties

3.2 配置文件

3.2.1 yaml

yml是YAML(YAML Ain’t Markup Language)语言的文件,以数据为中心,比properties、xml等更适合做配置文件

  • yml和xml相比,少了一些结构化的代码,使数据更直接,一目了然。
  • 相比properties文件更简洁

3.2.2 yaml语法
以空格的缩进程度来控制层级关系。空格的个数并不重要,只要左边空格对齐则视为同一个层级。且大小写敏感。支持字面值,对象,数组三种数据结构,也支持复合结构。

  • 字面值:字符串,布尔类型,数值,日期。字符串默认不加引号,单引号会转义特殊字符。日期格式支持yyyy/MM/dd HH:mm:ss
  • 对象:由键值对组成,形如 key:(空格)value 的数据组成。冒号后面的空格是必须要有的,每组键值对占用一行,且缩进的程度要一致,也可以使用行内写法:{k1: v1, …kn: vn}
  • 数组:由形如 -(空格)value 的数据组成。短横线后面的空格是必须要有的,每组数据占用一行,且缩进的程度要一致,也可以使用行内写法: [1,2,…n]
  • 复合结构:上面三种数据结构任意组合

3.2.3 yaml的运用

yaml:
  level:
    str: 字符串不需要加\n双引号
    specialStr: "字符串不需要加\n双引号"
    num: 666
    Dnum: 666.88
    birth: 2000/12/10 12:23:34
#    list:
#      - one
#      - two
#      - two
    list: [one, two]

#    set: [1,2,3,1]
    set:
      - 1
      - 2
      - 1
    map: {key1: value1, key2: value2}
    users:
      - name: zhangsan
        salary: 123.8
      - name: lisi
        salary: 888.00

@Component
@ConfigurationProperties(prefix = "yaml.level")
public class YamlModel {


    private String str;

    private String specialStr;

    private int num;

    private double Dnum;

    private Date birth;

    private List<String> list = new ArrayList<>();

    private Set<Integer> set = new HashSet<>();

    private Map<String, String> map = new HashMap<>();

    private List<User> users = new ArrayList<>();

3.2.4 总结

  • 字符串可以不加引号,若加双引号则输出特殊字符,若不加或加单引号则转义特殊字符;
  • 数组类型,短横线后面要有空格;对象类型,冒号后面要有空格;
  • YAML是以空格缩进的程度来控制层级关系,但不能用tab键代替空格,大小写敏感;
  • yaml的缺点是可读性比较差

3.3 属性绑定

  • 前面给大家讲了yaml的语法和绑定注入给实体类,那我们平时在工作中多数是在通过实体类来写yaml的配置。属性的绑定我们必须要提供set方法
@Data
@Component
@ConfigurationProperties("acme")
public class AcmeProperties {

    private boolean enabled;

    private InetAddress remoteAddress;

    private  Security security = new Security();

    @Data
    public static class Security {

        private String username;

        private String password;

        private List<String> roles = new ArrayList<>(Collections.singleton("USER"));

    }

}

为了让当前的实体类能在配置文件中有对应的提示,我们需要引入如下的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

在配置文件中加入

acme:
  enabled: true
  remote-address: 191.11.11.1
  security:
    roles: [明心,过去]
    password: 123
    username: 我的

然后我们测试绑定的情况。
在属性绑定的方式里,我们是通过set方法来完成的,我们可以借助Lombok来给我们带来方便。

我们在父工程中引入Lombok的依赖:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
</dependency>

修改属性类:加上@Data注解,然后测试结果相同。

3.4 构造器绑定

让我们采用构造器的方式来定义

@Data
@ConfigurationProperties("acme")
@ConstructorBinding
public class AcmeProperties {

    private boolean enabled;

    private InetAddress remoteAddress;

    private  Security security ;

    public AcmeProperties(boolean enabled, InetAddress remoteAddress, Security security) {
        this.enabled = enabled;
        this.remoteAddress = remoteAddress;
        this.security = security;
    }

    @Data
    public static class Security {

        private String username;

        private String password;

        private List<String> roles = new ArrayList<>(Collections.singleton("USER"));

        public Security(String username, String password, List<String> roles) {
            this.username = username;
            this.password = password;
            this.roles = roles;
        }
    }

}

要使用构造函数绑定,必须使用@EnableConfigurationProperties或配置属性扫描启用类。不能对由常规Spring机制创建的Bean使用构造函数绑定(例如@Component Bean、通过@Bean方法创建的Bean或使用@Import加载的Bean)
测试的Controller

@RestController
@EnableConfigurationProperties(AcmeProperties.class)
public class YamlController {
    @Autowired
    private AcmeProperties acmeProperties;


    @RequestMapping("test")
    public AcmeProperties test(){
        return acmeProperties;
    }
}

  • 测试成功。在属性绑定的案例中我们同样也可以使用@EnableConfigurationProperties,此时不需要提供@Component

  • 如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了启用注入。

3.5 第三方组件注入

  • 除了使用@ConfigurationProperties注释类之外,还可以在public@Bean方法上使用它。如果要将属性绑定到不在您控制范围内的第三方组件
  • 依然采用之前的案例的yaml配置
    创建一个其他组件类
@Data
public class AnotherProperties {
    private boolean enabled;

    private InetAddress remoteAddress;

}

创建MyService

@Component
@Validated
public class MyService {

    @Bean
    @ConfigurationProperties("acme")
    public AnotherProperties getAnotherProperties(){
        return new AnotherProperties();
    }
}

我们通过测试可以获得AnotherComponent组件的实例对象。

3.6 松散绑定

Spring Boot使用一些宽松的规则将环境属性绑定到@ConfigurationProperties bean,因此环境属性名和bean属性名之间不需要完全匹配。
例如属性类:

@Data
@Component
@ConfigurationProperties("acme.my-person.person")
public class OwnerProperties {

    private String firstName;

}

配置文件:

acme:
  my-person:
    person:
      first-name: 泰森

在这里插入图片描述

3.7 @ConfigurationProperties 校验

  • 每当使用Spring的@Validated注释对@ConfigurationProperties类进行注释时,Spring Boot就会尝试验证它们。你可以用JSR-303 javax.validation直接在配置类上的约束注释。为此,请确保类路径上有一个兼容的JSR-303实现,此处我们用的是hibernate的实现,然后将约束注释添加到字段中

1.引入依赖

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.2.0.Final</version>
</dependency>

2.在属性类上加入注解

@Data
@Component
@ConfigurationProperties("acme.my-person.person")
@Validated
public class OwnerProperties {

    @NotNull
    private String firstName;

    @Max(30)
    private Integer age;

    @Email
    private String  email;

    private School school=new School();

    @Data
    class School{
        private String name;
    }
}
**3.配置文件**
acme:
  my-person:
    person:
      FIRST_name: 泰森
      age: 34
      email: aaa
 启动主启动类的时候,会自动发生校验。

在这里插入图片描述

3.8 @ConfigurationProperties vs. @Value

1.松散绑定在@value是被限制的

  • 如果您确实想使用@Value,建议引用属性名(kebab case只使用小写字母,既是羊肉串模式)。这允许Spring Boot使用与放松binding@ConfigurationProperties时相同的逻辑。例如,@Value(“${demo.item-price})将匹配demo.item-price和demo.itemPrice, 其他模式不能匹配。

2.元数据支持

  • 我们在@ConfigurationProperties方式可以生成元数据,目的是给我们提供提示和属性的描述。但是在@value里面是没有的。@Value适合单个的属性注入

3.spEL在@ConfigurationProperties中是不能支持的。在@Value中可以支持
如:
在这里插入图片描述

4.@Value复杂类型不可注入,会有启动报错。

3.9 Profile

我们可以通过多样性的文档来解决多环境的需求。在一个yml中我们可以把文档划分成多个块

acme:
  enabled: true
  remote-address: 191.11.11.1
#spring:
#  profiles:
#    active: dev
---
acme:
  enabled: true
  remote-address: 191.11.11.2
spring:
  profiles: pro
---
acme:
  enabled: true
  remote-address: 191.11.11.3
spring:
  profiles: dev

在启动的时候我们通过spring.profiles.active: development来指定开启哪个profile
我们也可以采用多个文件来做。
我们创建application-dev.yml, application-pro.yml
application-{profile}.xml
在这里插入图片描述
属性类:

@Data
@Component
@ConfigurationProperties("acme")
public class AcmeProperties {

    private boolean enabled;

    private InetAddress remoteAddress;

    private String port;

}

我们可以通过profile的指定来启用指定的文件。
application-dev.yml

acme:
  enabled: true
  remote-address: 191.11.11.3
  host: ${acme.remote-address}:8080

application-pro.yml

acme:
  enabled: true
  remote-address: 191.11.11.2
  host: ${acme.remote-address}:8081

  • 我们依然在启动的时候我们通过spring.profiles.active: development来指定。
  • 我们可以通过${}方式获取当前文档中配置和jvm的参数中的配置值。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值