SpringBoot(一)(运行原理、属性赋值、校验、多环境配置)

1、什么是SpringBoot?

  • 随着 Spring 不断的发展,涉及的领域越来越多,项目整合开发需要配合各种各样的文件,慢慢变得不那么易用简单,违背了最初的理念,甚至人称配置地狱。Spring Boot 正是在这样的一个背景下被抽象出来的开发框架,目的为了让大家更容易的使用 Spring 、更容易的集成各种常用的中间件、开源软件。
  • 简单来说就是SpringBoot其实不是什么新的框架,它默认配置了很多框架的使用方式,就像maven整合了所有的jar包,spring boot整合了所有的框架 。

2、运行原理

(1)pom配置文件

其中主要是依赖一个父项目,主要是管理项目的资源过滤及插件

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

点进去,就会发现它还有一个父依赖,这里才是真正管理SpringBoot应用里面所有依赖版本的地方,版本控制中心。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.3.1.RELEASE</version>
</parent>

启动器 spring-boot-starter-web

<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • spring-boot-starter-xxx:就是SpringBoot的场景启动器
  • spring-boot-starter-web:导入web模块正常运行所依赖的组件
    SpringBoot将所有的功能场景都抽取出来,做成一个个的starter(启动器),只需要在项目中引入这些starter即可,所有相关的依赖都会导入进来,我们需要什么功能就导入什么样的场景启动器即可。
(2)主启动类
//@SpringBootApplication用来标注一个主程序类
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

点进去之后,发现还有几个注解

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
}
  • @ComponentScan:自动扫描并加载符合条件的组件或者bean,将这个bean定义加载到IOC容器中。

  • @SpringBootConfiguration:SpringBoot的配置类,表示该类是一个SpringBoot的配置类

@Configuration//说明这是一个配置类,配置类对应Spring的XML文件
public @interface SpringBootConfiguration {}
@Component//启动类本身也是Spring中的一个组件而已。
public @interface Configuration {}
  • @EnableAutoConfiguration:开启自动配置功能
@AutoConfigurationPackage:自动配置包
@Import({AutoConfigurationImportSelector.class}):给容器带入组件,自动配置导入选择器。
(3)SpringApplication
SpringApplication.run(DemoApplication.class, args);

该方法主要分为两部分,一部分是SpringApplication的实例化,另一部分是run方法的执行。

  • Springpplication的实例化
1、推断应用的类型是普通的项目还是Web项目
2、查找并加载所有可用初始化器 , 设置到initializers属性中。
3、找出所有的应用程序监听器,设置到listeners属性中。
4、推断并设置main方法的定义类,找到运行的主类。
  • run方法的执行

在这里插入图片描述

3、给属性赋值

(1)之前采用的是@Value注解来完成的
(2)使用@ConfigurationProperties

@Component
//绑定实体类与配置类
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private List<Object> hobby;
    private Dog dog;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<Object> getHobby() {
        return hobby;
    }
    public void setHobby(List<Object> hobby) {
        this.hobby = hobby;
    }
    public Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public Person() {
    }
    public Person(String name, List<Object> hobby, Dog dog) {
        this.name = name;
        this.hobby = hobby;
        this.dog = dog;
    }

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

application.yml给属性赋值

person:
  name: ttt
  hobby: [code,music]
  dog:
     name: coco
     age: 3

解决解析yml文件时会出现中文乱码的问题
在这里插入图片描述
(3)使用@PropertySource

@Component
//绑定实体类与配置类
/*@ConfigurationProperties(prefix = "person")*/
@PropertySource(value = "classpath:application.properties")
public class Person {
    @Value("${name}")
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Person() {
    }
    public Person(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

结论

  • 配置yml和配置properties都可以获取到值,强烈推荐yml。
  • 如果我们在某个业务中,只需要获取到配置文件中的某个值,可以使用一下@Value。
  • 如果专门编写了一个JavaBean和配置文件来进行映射,就直接使用@ConfigurationProperties。

4、JSR303校验

引入依赖

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

@Email邮箱校验

@Component
//绑定实体类与配置类
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
    @Email(message="邮箱格式错误")
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Person() {
    }
    public Person(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

常见的校验参数

@NotNull(message="名字不能为空")
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@Email(message="邮箱格式错误")
private String email;

空检查
@Null       验证对象是否为null
@NotNull    验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank   检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty   检查约束元素是否为NULL或者是EMPTY.
    
Booelan检查
@AssertTrue     验证 Boolean 对象是否为 true  
@AssertFalse    验证 Boolean 对象是否为 false  
    
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  
@Length(min=, max=) string is between min and max included.

日期检查
@Past       验证 Date 和 Calendar 对象是否在当前时间之前  
@Future     验证 Date 和 Calendar 对象是否在当前时间之后  
@Pattern    验证 String 对象是否符合正则表达式的规则

5、多环境配置

我们在实际的项目开发中,可能需要不同的环境,比如开发时需要开发环境、测试环境、项目上线环境等,我们可以配置多个环境,在需要的时候切换即可。

使用application.yml配置非常方便

server:
  port: 8080 #默认的环境是8080
spring:
  profiles:
    active: test #切换环境
---
server:
  port: 8081
spring:
  profiles: test  #测试环境
---
server:
  port: 8082
spring:
  profiles: dev  #上线环境

6、自动配置原理

我们通过研究发现,在yml里面配置的一些属性都有对应的一个Poperties实体类,我们以Server.port为例来说明。

//这个注解就是前面说的属性配置的注解
@ConfigurationProperties( prefix = "server", ignoreUnknownFields = true)
//yml中的每个配置属性都有一个xxxProperties对应,
public class ServerProperties {
    private Integer port;
    private InetAddress address;
    @NestedConfigurationProperty
    private final ErrorProperties error = new ErrorProperties();
    private ServerProperties.ForwardHeadersStrategy forwardHeadersStrategy;
    private String serverHeader;
    private DataSize maxHttpHeaderSize = DataSize.ofKilobytes(8L);
    private Shutdown shutdown;
    @NestedConfigurationProperty
    private Ssl ssl;
    @NestedConfigurationProperty
    private final Compression compression;
    @NestedConfigurationProperty
    private final Http2 http2;
    private final ServerProperties.Servlet servlet;
    private final ServerProperties.Tomcat tomcat;
    private final ServerProperties.Jetty jetty;
    private final ServerProperties.Netty netty;
    private final ServerProperties.Undertow undertow;

    public ServerProperties() {
        this.shutdown = Shutdown.IMMEDIATE;
        this.compression = new Compression();
        this.http2 = new Http2();
        this.servlet = new ServerProperties.Servlet();
        this.tomcat = new ServerProperties.Tomcat();
        this.jetty = new ServerProperties.Jetty();
        this.netty = new ServerProperties.Netty();
        this.undertow = new ServerProperties.Undertow();
    }
    public Integer getPort() {
        return this.port;
    }
    public void setPort(Integer port) {
        this.port = port;
    }
    ......

我们可以使用下面的这个配置来查看配置是否生效

debug: true
- Positive matches:表示已经配置的并且生效的
- Negative matches:没有配置的
- Unconditional classes:没有条件的

我们以ActiveMq分析一下

spring:
  activemq:
    non-blocking-redelivery: true #点进去之后
@ConfigurationProperties(
    prefix = "spring.activemq"
)
public class ActiveMQProperties {
    private String brokerUrl;
    private boolean inMemory = true;
    private String user;
    private String password;
    private Duration closeTimeout = Duration.ofSeconds(15L);
    private boolean nonBlockingRedelivery = false;
    .....
    }

找到一个ActiveMQAutoConfiguration 的类

@Configuration(
    proxyBeanMethods = false
)
@AutoConfigureBefore({JmsAutoConfiguration.class})
@AutoConfigureAfter({JndiConnectionFactoryAutoConfiguration.class})
@ConditionalOnClass({ConnectionFactory.class, ActiveMQConnectionFactory.class})
@ConditionalOnMissingBean({ConnectionFactory.class})
@EnableConfigurationProperties({ActiveMQProperties.class, JmsProperties.class})
@Import({ActiveMQXAConnectionFactoryConfiguration.class, ActiveMQConnectionFactoryConfiguration.class})
public class ActiveMQAutoConfiguration {
    public ActiveMQAutoConfiguration() {
    }
}

我们发现,没有导入ActiveMQ的依赖时上面是报红的,而在Springboot中都是启动器,所以只要找到ActiveMQ的启动器然后再pom.xml中引入即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值