黑河网站制作,织梦做的网站首页被篡改,国家学历提升官网,江苏建设厅老网站优质博文#xff1a;IT-BLOG-CN
一、Spring Boot全局配置文件
application.properties与application.yml配置文件的作用#xff1a;可以覆盖SpringBoot配置的默认值。
◀ YML#xff08;is not a Markup Language#xff1a;不仅仅是一个标记语言#xff09;#xff1…优质博文IT-BLOG-CN
一、Spring Boot全局配置文件
application.properties与application.yml配置文件的作用可以覆盖SpringBoot配置的默认值。
◀ YMLis not a Markup Language不仅仅是一个标记语言 以前的配置文件大多是xx.xml文件而YAML是以数据为中心比json、xml等更适合做配置文件。
#普通配置文件.properties的语法
#server.port80#XML的写法
#server
# port8080port/
#server/#yml 以数据为中心的语法
server:port: 8080◀ YML语法 基本语法k:空格v—表示一对键值对。以空格缩进来控制层级关系只要是左对齐的一列数据都是同一层级属性和值也是大小写敏感。
server:port: 8080path: /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: zhangsanage: 20boss: falsebirth: 2018/8/20map: {k1: v1,k2: v2}lists: [listi,zhaoliu]dog:name: gouage: 2【2】准备JavaBeanConfigurationProperties(prefix person) 表示将配置文件中的person的每一个属性映射到这个组件中但只有这个组件是容器中的组件才能提供功能。需要使用Component标注才能成为容器组件。
Component
ConfigurationProperties(prefix person)
public class Person {private String lastName;private Integer age;private boolean boss;private Date birth;private MapString,String map;private List lists;private Dog dog;
}【3】优化当准备2中的文件会提示我们 “Spring Boot Configuration Annotation …” 点击去后会发现如下starters信息那么我们将此配置于pom文件中作用当我们在配置文件中给带有 ConfigurationProperties的实体类赋值时会有属性提示。
dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-configuration-processor/artifactIdoptionaltrue/optional
/dependency【4】测试 进入test目录底下的类目录直接导入person输入查看是否已赋值即可。
//使用Spring的驱动器不用再使用JUnit的驱动器了
RunWith(SpringRunner.class)
SpringBootTest
public class HellowordQuickStartApplicationTests {//在测试期间可以类似编码一样进行自动注入AutowiredPerson person;Testpublic void testPersion(){System.out.println(person);}
}【5】properties中的语句与yml不同以下是properties的配置语句。
#person.lastName张三 也是可以的
person.last-name张三
person.age18
person.birth2013/04/23
person.bossfalse
person.map.key1v1
person.map.key2v2
person.listsa,b,c
person.dog.namedog
person.dog.age2【6】测试的时候可能会出现乱码设置如下。properties默认的编码时ASK码我们需要将其设置为UTF-8来解决乱码问题。 【7】第二种赋值方式Value“字面量/${key}从环境变量、配置文件中获取值/#{SpEL}”—三种传值方式
Component
//ConfigurationProperties(prefix person)
public class Person {//email Value不支持校验JSR303数据校验Value(${person.last-name})private String lastName;//SPELValue(#{22*3})private Integer age;Value(true)private boolean boss;Vaule与ConfigurationProperties两者的区别如下其实Value最多用在获取单个值的时候使用
configurationvalue功能批量注入配置文件中的属性每个属性单独配置松散绑定松散语法支持大小写不敏感不支持与配置文件保持一致SpEL不支持不能用于逻辑计算支持#{逻辑计算}JSR303数据校验支持validated不支持复杂类型封装支持不支持map对象
二、PropertySource 与 ConfigurationProperties之间的区别
ConfigurationProperties默认从全局配置文件中加载值。
● PropertySource指向自己定义的properties配置文件新建person.properties配置文件省略如下获取值。
//优先级高于ConfigurationProperties(prefix person)
PropertySource(value {classpath:person.properties})
Component
//ConfigurationProperties(prefix person)
//Validated
public class Person {● ImportResource导入Spring的配置文件让配置文件里面的内容生效。 1、定义配置文件bean.xml以前的配置SpringBoot不这么用
?xml version1.0 encodingUTF-8?
beans xmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdbean idhelloService classcom.atguigu.Servers.HelloService/bean
/beans2、在主程序中使用ImportResource注解导入bean.xml配置文件
ImportResource(locations{classpath:bean.xml})
SpringBootApplication
public class HellowordQuickStartApplication {● SpringBoot中配置类配置文件xml推荐使用配置类如下创建
//Configuration指明当前类是一个配置类 替代配置文件
Configuration
public class MyAppConfig {//bean注解就相当于bean/bean标签Bean//方法名就相当于xml中的id 项目启动时就会将组件加入容器中public HelloService helloService(){System.out.println(Bean给容器中添加组件);return new HelloService();}
}三、配置文件占位符
【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: 8084
spring:profiles: prod
---
server:port: 8081
spring:profiles:active: dev【3】激活指定profile方式上面用的都是第一种 1在默认配置application.properties中设置spring.profiles.active属性
spring.profiles.activedev2命令行--spring.profiles.activedev 命令行运行 jar包的方式java -jar xxx.jar --spring.profiles.activedev; 3虚拟机参数-Dspring.profiles.activeprod; 五、配置文件加载位置也就优先级
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.locationd:\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】每一个自动配置类进行自动配置功能以 HttpEncodingAutoConfigurationHttp编码自动配置为例解释自动配置原理
Configuration //表示这是一个配置类以前编写的配置文件一样也可以给容器中添加组件
EnableConfigurationProperties(HttpEncodingProperties.class) //启动指定类的
//ConfigurationProperties功能将配置文件中对应的值和HttpEncodingProperties绑定起来并把
//HttpEncodingProperties加入到ioc容器中
ConditionalOnWebApplication //Spring底层Conditional注解Spring注解版根据不同的条件如果
//满足指定的条件整个配置类里面的配置就会生效 判断当前应用是否是web应用如果是当前配置类生效
ConditionalOnClass(CharacterEncodingFilter.class) //判断当前项目有没有这个类
//CharacterEncodingFilterSpringMVC 中进行乱码解决的过滤器
//判断配置文件中是否存在某个配置 spring.http.encoding.enabled如果不存在判断也是成立的
ConditionalOnProperty(prefix spring.http.encoding, value enabled, matchIfMissing true)
//即使我们配置文件中不配置pring.http.encoding.enabledtrue也是默认生效的
public class HttpEncodingAutoConfiguration {//他已经和SpringBoot的配置文件映射了private final HttpEncodingProperties properties;//只有一个有参构造器的情况下参数的值就会从容器中拿public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {this.properties properties;}Bean //给容器中添加一个组件这个组件的某些值需要从properties中获取ConditionalOnMissingBean(CharacterEncodingFilter.class) //判断容器没有这个组件public CharacterEncodingFilter characterEncodingFilter() {CharacterEncodingFilter filter new OrderedCharacterEncodingFilter();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的属性进行绑定
public class HttpEncodingProperties {
public static final Charset DEFAULT_CHARSET Charset.forName(UTF‐8);精髓 【1】SpringBoot 启动会加载大量的自动配置类 【2】我们看我们需要的功能有没有SpringBoot默认写好的自动配置类 【3】我们再来看这个自动配置类中到底配置了哪些组件只要我们要用的组件有我们就不需要再来配置了 【4】给容器中自动配置类添加组件的时候会从properties类中获取某些属性。我们就可以在配置文件中指定这些属性的值
xxxxAutoConfigurartion自动配置类给容器中添加组件。xxxxProperties封装配置文件中相关属性
七、ConditionalOnxxx 中的 Conditional 派生注解Spring注解版原生的Conditional作用作用
必须是Conditional指定的条件成立才给容器中添加组件配置配里面的所有内容才生效。
Condition扩展注解作用(判断是否满足当前指定条件)ConditionalOnJava系统的 Java版本是否符合要求ConditionalOnBean容器中存在指定BeanConditionalOnMissingBean容器中不存在指定BeanConditionalOnExpression满足SpEL表达式指定ConditionalOnClass系统中有指定的类ConditionalOnMissingClass系统中没有指定的类ConditionalOnSingleCandidate容器中只有一个指定的Bean或者这个Bean是首选BeanConditionalOnProperty系统中指定的属性是否有指定的值ConditionalOnResource类路径下是否存在指定资源文件ConditionalOnWebApplication当前是web环境ConditionalOnNotWebApplication当前不是web环境ConditionalOnJndiJNDI存在指定项
● 自动配置类必须在一定的条件下才能生效那么我们如何知道哪些配置类生效哪些没有生效其实我们可以通过在配置文件启用 debugtrue属性就可以查看哪些配置类生效。
debugtrue▶ 通过控制台打印自动配置报告我们就可以知道哪些自动配置类生效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)