0


SpringBoot——配置及原理

优质博文:IT-BLOG-CN

一、Spring Boot全局配置文件

application.properties

application.yml

配置文件的作用:可以覆盖

SpringBoot

配置的默认值。

YML(is not a Markup Language:不仅仅是一个标记语言): 以前的配置文件,大多是

xx.xml

文件,而

YAML

是以数据为中心,比

json、xml

等更适合做配置文件。

#普通配置文件.properties的语法
#server.port=80

#XML的写法
#<server>
#   <port>8080<port/>
#<server/>

#yml 以数据为中心的语法
server:
  port: 8080

YML语法: 基本语法:k:(空格)v—>表示一对键值对。(以空格缩进来控制层级关系;只要是左对齐的一列数据,都是同一层级)属性和值也是大小写敏感。

server:
  port: 8080
  path: /hello
spring:
  profiles: dev

值的写法:

【1】字面量:普通的值(数字、字符串、布尔),字符串默认是不用加上单引号或者双引号,但也可以加,但是有区别:双引号,不会转义字符串里面的特殊字符,特殊字符会作为本身想表达的意思。单引号,会转义特殊字符,特殊字符最终只是一个普通的字符串数据。
【2】对象(属性和值)或者Map(键值对)的表达[k: v]形式,对象也是[k: v]的方式。比较抽象,我们举个栗子看看:

#yml正常写法friends:lastName: zhangsan           
    age:20#行内写法friends:{lastName: zhangsan,age:20}

【3】数组(List、Set)用 [- 值]表示数组中的一个元素,也举一个栗子:

# yml正常写法 -值 形式pets:- cat
   - dog
#行内写法pets:[cat,dog]

配置文件注入: 测试上面数据赋值是否正确。

【1】准备配置文件:

application.yml
person:lastName: zhangsan
  age:20boss:falsebirth: 2018/8/20
  map:{k1: v1,k2: v2}lists:[listi,zhaoliu]dog:name: gou
    age:2

【2】准备

JavaBean

@ConfigurationProperties(prefix ="person")

表示将配置文件中的

person

的每一个属性映射到这个组件中,但只有这个组件是容器中的组件,才能提供功能。需要使用

@Component

标注才能成为容器组件。

@Component@ConfigurationProperties(prefix ="person")publicclassPerson{privateString lastName;privateInteger age;privateboolean boss;privateDate birth;privateMap<String,String> map;privateList lists;privateDog dog;}

【3】优化:当准备2中的文件,会提示我们 “Spring Boot Configuration Annotation …” 点击去后会发现如下

starters

信息,那么我们将此配置于

pom

文件中,作用:当我们在配置文件中,给带有 @ConfigurationProperties的实体类赋值时会有属性提示。

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

【4】测试: 进入

test

目录底下的类目录,直接导入

person

输入,查看是否已赋值即可。

//使用Spring的驱动器,不用再使用JUnit的驱动器了@RunWith(SpringRunner.class)@SpringBootTestpublicclassHellowordQuickStartApplicationTests{//在测试期间可以类似编码一样进行自动注入@AutowiredPerson person;@TestpublicvoidtestPersion(){System.out.println(person);}}

【5】

properties

中的语句与

yml

不同,以下是

properties

的配置语句。

#person.lastName=张三 也是可以的
person.last-name=张三
person.age=18
person.birth=2013/04/23
person.boss=false
person.map.key1=v1
person.map.key2=v2
person.lists=a,b,c
person.dog.name=dog
person.dog.age=2

【6】测试的时候可能会出现乱码,设置如下。

properties

默认的编码时

ASK

码,我们需要将其设置为

UTF-8

来解决乱码问题。

【7】第二种赋值方式:

@Value

(“字面量/

${key}

从环境变量、配置文件中获取值/

#{SpEL}

”)—三种传值方式

@Component//@ConfigurationProperties(prefix ="person")publicclassPerson{//@email @Value不支持校验(JSR303数据校验)@Value("${person.last-name}")privateString lastName;//SPEL@Value("#{22*3}")privateInteger age;@Value("true")privateboolean boss;
@Vaule

@ConfigurationProperties

两者的区别如下:(其实

@Value

最多用在获取单个值的时候使用)
@configuration@value功能批量注入配置文件中的属性每个属性单独配置松散绑定(松散语法)支持(大小写不敏感)不支持(与配置文件保持一致)SpEL不支持(不能用于逻辑计算)支持#{逻辑计算}JSR303数据校验支持@validated不支持复杂类型封装支持不支持(map对象)

二、@PropertySource 与 @ConfigurationProperties之间的区别

@ConfigurationProperties

:默认从全局配置文件中加载值。

@PropertySource

:指向自己定义的

properties

配置文件,新建

person.properties

配置文件(省略),如下获取值。

//优先级高于@ConfigurationProperties(prefix ="person")@PropertySource(value ={"classpath:person.properties"})@Component//@ConfigurationProperties(prefix ="person")//@ValidatedpublicclassPerson{

@ImportResource

:导入

Spring

的配置文件,让配置文件里面的内容生效。
 1)、定义配置文件

bean.xml

(以前的配置,

SpringBoot

不这么用)

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd"><beanid="helloService"class="com.atguigu.Servers.HelloService"></bean></beans>

 2)、在主程序中使用

@ImportResource

注解导入

bean.xml

配置文件

@ImportResource(locations={"classpath:bean.xml"})@SpringBootApplicationpublicclassHellowordQuickStartApplication{

SpringBoot

中(配置类====配置文件xml)推荐使用配置类,如下创建:

//@Configuration指明当前类是一个配置类 替代配置文件@ConfigurationpublicclassMyAppConfig{//@bean注解就相当于<bean></bean>标签@Bean//方法名就相当于xml中的id , 项目启动时就会将组件加入容器中publicHelloServicehelloService(){System.out.println("@Bean给容器中添加组件");returnnewHelloService();}}

三、配置文件占位符

【1】随机数(了解即期)

${random.value}、${random.int}、${random.log}、${random.int(10)}

【2】占位符(当属性不存在时,可以给一个默认值,例如下面age属性值得获取)

persion.last-name=张三
persion.dog.name=${persion.last_name}_dog
perdion.dog.age=${persion.noexistage:20}

四、Profile

Profile:

Spring

对不同环境提供不同配置功能的支持,可以通过激活、指定参数等方式快速切换环境。

【1】多

profile

文件形式(了解一下,我们使用更多的是2中的

yml

形式):我们可以编写多个配置文件,对应多个场景(开发、测试、生产等),文件名可以是

application-{profile}.properties/yml

的形式命名,例如:

application-dev.properties

项目启动时默认使用

application.properties

的配置,如果要激活开发配置文件,在

application.properties

中输入如下激活信息。

#激活dev开发模式的配置文件,就不用application.properties文件的配置了

【2】

yml

支持多文档块方式(推荐使用):通过“—”来划分文档块,

Document

表示所处模块的位置/总块 。

# --- 称为多文档快 , 简写1中的形式---server:port:8080path: /hello
# 如下为激活profiles ,如果不激活则默认为Document1中的配置spring:profiles:active: dev
---server:port:8084spring:profiles: prod
---server:port:8081spring:profiles:active: dev

【3】激活指定

profile

方式,上面用的都是第一种:
 1)在默认配置

application.properties

中设置

spring.profiles.active

属性

spring.profiles.active=dev

 2)命令行:

--spring.profiles.active=dev

命令行运行 jar包的方式:java -jar xxx.jar --spring.profiles.active=dev;

 3)虚拟机参数:-Dspring.profiles.active=prod;

五、配置文件加载位置:也就优先级

SpringBoot

启动时会扫描以下位置的

application.properties

或者

application.yml

文件作为

SpringBoot

的默认配置文件:
【1】

file:./config/ 

(项目底下的config目录)
【2】

file:./

(直接位于项目底下的配置文件)
【3】

classpath:/config/

(config文件默认没生成,需要自己创建)
【4】

classpath:/

(项目创建后,配置文件默认位置)
以上是按照优先级从高到低的顺序,所有位置的文件都会被加载,高优先级配置内容会覆盖低优先级配置的相同内容。
我们也可以通过 spring.config.location 来改变默认配置(项目打包成功以后,我们可以使用命令行参数的形式,启动项目来指定配置文件的新位置;指定的配置文件会共同起作用,形成互补作用),这个优先级肯定最高了。而且我们要知道,打jar包的时候只包含src底下的main和resource文件,1、2中的不会被打包进去。其实将jar包与配置文件*.yml等放在同一个目录下的情况也比较多常见,因为灵活。项目启动时可以自动加载同目录下的*.yml等配置文件。且优先级高于内部的配置文件,之间互补配置。

#命令行添加配置,优先级最高
java -jar xxx.jar --spring.config.location=d:\xxx.properties

六、自动配置原理

【1】

SpringBoot

启动的时候加载主配置类,

@SpringBootApplication

下开启了主配置功能

@EnableAutoConfiguration

【2】

@EnableAutoConfiguration

作用:
 ①、利用

EnableAutoConfigurationImportSelector

给容器导入一些组件。
 ②、可以查看

selectImports()

方法的内容:

List configurations = getCandidateConfigurations(annotationMetadata, attributes);

获取候选的配置。

SpringFactoriesLoader.loadFactoryNames()

扫描所有

jar

包类路径下

META‐INF/spring.factories

把扫描到的这些文件的内容包装成

properties

对象从

properties

中获取到

EnableAutoConfiguration.class

类(类名)对应的值,然后把他们添加在容器中。
【3】将类路径下

META-INF/spring.factories

里面配置的所有

EnableAutoConfiguration

的值加入到了容器中;

# EnableAutoConfiguration  对应 @EnableAutoConfiguration
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\

每一个这样的

xxxAutoConfiguration

类都是容器中的一个组件,都加入到容器中。用他们来做自动配置;

【4】每一个自动配置类进行自动配置功能,以 HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理;

@Configuration//表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件@EnableConfigurationProperties(HttpEncodingProperties.class)//启动指定类的//ConfigurationProperties功能;将配置文件中对应的值和HttpEncodingProperties绑定起来;并把//HttpEncodingProperties加入到ioc容器中@ConditionalOnWebApplication//Spring底层@Conditional注解(Spring注解版),根据不同的条件,如果//满足指定的条件,整个配置类里面的配置就会生效; 判断当前应用是否是web应用,如果是,当前配置类生效@ConditionalOnClass(CharacterEncodingFilter.class)//判断当前项目有没有这个类//CharacterEncodingFilter;SpringMVC 中进行乱码解决的过滤器;//判断配置文件中是否存在某个配置 spring.http.encoding.enabled;如果不存在,判断也是成立的@ConditionalOnProperty(prefix ="spring.http.encoding", value ="enabled", matchIfMissing =true)//即使我们配置文件中不配置pring.http.encoding.enabled=true,也是默认生效的;publicclassHttpEncodingAutoConfiguration{//他已经和SpringBoot的配置文件映射了privatefinalHttpEncodingProperties properties;//只有一个有参构造器的情况下,参数的值就会从容器中拿publicHttpEncodingAutoConfiguration(HttpEncodingProperties properties){this.properties = properties;}@Bean//给容器中添加一个组件,这个组件的某些值需要从properties中获取@ConditionalOnMissingBean(CharacterEncodingFilter.class)//判断容器没有这个组件?publicCharacterEncodingFiltercharacterEncodingFilter(){CharacterEncodingFilter filter =newOrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));return filter;}

根据当前不同的条件判断,决定这个配置类是否生效?一但这个配置类生效;这个配置类就会给容器中添加各种组件;这些组件的属性是从对应的

properties

类中获取的,这些类里面的每一个属性又是和配置文件绑定的;

【5】所有在配置文件中能配置的属性都是在

xxxxProperties

类中封装;配置文件能配置什么就可以参照某个功能对应的属性类

@ConfigurationProperties(prefix ="spring.http.encoding")//从配置文件中获取指定的值和bean的属性进行绑定publicclassHttpEncodingProperties{publicstaticfinalCharsetDEFAULT_CHARSET=Charset.forName("UTF‐8");

精髓:
【1】SpringBoot 启动会加载大量的自动配置类;
【2】我们看我们需要的功能有没有SpringBoot默认写好的自动配置类;
【3】我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件有,我们就不需要再来配置了)
【4】给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们就可以在配置文件中指定这些属性的值;

xxxxAutoConfigurartion

:自动配置类,给容器中添加组件。

xxxxProperties

:封装配置文件中相关属性;

七、@ConditionalOnxxx 中的 @Conditional 派生注解(Spring注解版原生的@Conditional作用)作用

必须是

@Conditional

指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效。
@Condition扩展注解作用(判断是否满足当前指定条件)@ConditionalOnJava系统的 Java版本是否符合要求@ConditionalOnBean容器中存在指定Bean@ConditionalOnMissingBean容器中不存在指定Bean@ConditionalOnExpression满足SpEL表达式指定@ConditionalOnClass系统中有指定的类@ConditionalOnMissingClass系统中没有指定的类@ConditionalOnSingleCandidate容器中只有一个指定的Bean,或者这个Bean是首选Bean@ConditionalOnProperty系统中指定的属性是否有指定的值@ConditionalOnResource类路径下是否存在指定资源文件@ConditionalOnWebApplication当前是web环境@ConditionalOnNotWebApplication当前不是web环境@ConditionalOnJndiJNDI存在指定项
● 自动配置类必须在一定的条件下才能生效,那么我们如何知道哪些配置类生效哪些没有生效,其实我们可以通过在配置文件启用 debug=true属性,就可以查看哪些配置类生效。

debug=true

▶ 通过控制台打印自动配置报告,我们就可以知道哪些自动配置类生效(Positive matches:匹配成功的自动配置类)

Positive matches:-----------------CodecsAutoConfiguration matched:- @ConditionalOnClass found required class 'org.springframework.http.codec.CodecConfigurer'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)

   CodecsAutoConfiguration.JacksonCodecConfiguration matched:- @ConditionalOnClass found required class 'com.fasterxml.jackson.databind.ObjectMapper'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)

   CodecsAutoConfiguration.JacksonCodecConfiguration#jacksonCodecCustomizer matched:- @ConditionalOnBean (types:com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found bean 'jacksonObjectMapper' (OnBeanCondition)

   DispatcherServletAutoConfiguration matched:- @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
      - found ConfigurableWebEnvironment (OnWebApplicationCondition)

▶ 自动配置未生效类[

Negative matches

:匹配失败的自动配置类]

Negative matches:-----------------ActiveMQAutoConfiguration:Did not match:- @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)

   AopAutoConfiguration:Did not match:- @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect','org.aspectj.lang.reflect.Advice', 'org.aspectj.weaver.AnnotatedElement' (OnClassCondition)

   ArtemisAutoConfiguration:Did not match:- @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory' (OnClassCondition)
标签: spring boot java spring

本文转载自: https://blog.csdn.net/zhengzhaoyang122/article/details/134619890
版权归原作者 程序猿进阶 所有, 如有侵权,请联系我们删除。

“SpringBoot——配置及原理”的评论:

还没有评论