欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot 配置文件

程序员文章站 2022-05-03 15:52:11
...

1. @ConfigurationProperties

  1. 告诉SpringBoot将本类中的所有字段和配置文件中相关的属性进行绑定
  2. 值prefix = "person"意为配置文件中person下面的所有属性与IOC容器中的person对象字段进行一一映射
  3. 只有这个组件是容器中的组件(配置类加@Component),才能容器提供的@ConfigurationProperties功能

Person类

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private Integer age;
    private Date birthday;
    private Boolean manager;
    private List<Object> pets;
    private Map<String, Object> maps;
    private Car car;
}

1.1 yml配置

application.yml

person:
  name: 张三
  age: 22
  birthday: 1990/04/20
  manager: true
  pets:
    - dog
    - cat
  maps: {v1: k1,v2: k2}
  car:
    name: 法拉利
    price: 5000000

运行结果对象的json:

{"name":"张三","age":22,"birthday":640540800000,"manager":true,"pets":["dog","cat"],"maps":{"v1":"k1","v2":"k2"},"car":{"name":"法拉利","price":5000000.0}}

1.2 properties配置

application.properties

person.name=张三
person.age=22
person.birthday=1990/04/20
person.manager=false
person.pets=dog,cat
person.maps.k1=v1
person.maps.k2=v2
person.car.name=Porche
person.car.price=3000000

配置properties的编码,避免乱码
Spring Boot 配置文件
运行结果对象的json:

{"name":"张三","age":22,"birthday":640540800000,"manager":false,"pets":["dog","cat"],"maps":{"k1":"v1","k2":"v2"},"car":{"name":"Porche","price":3000000.0}}

2. @Value

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

	// SpEL方式注入
    @Value("#{person.age}")
    private Integer age;
  • @Value获取值和@ConfigurationProperties获取值比较
@ConfigurationProperties @Value
功能 批量注入配置文件中的属性 一个个指定
松散绑定 支持 不支持
SpEL 不支持 支持
JSR303数据校验 支持 不支持
复杂类型封装 支持 不支持
  • 松散绑定指的是不区分fileName、file_name、file-name这三类属性配置写法

  • JSR303数据校验是@Validated结合一些其他注解做校验
    Spring Boot 配置文件
    Spring Boot 配置文件

  • 配置文件yml还是properties他们都能获取到值;

  • 如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value;

  • 如果说,我们专门编写了一个JavaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties;


3. @PropertySource

将配置文件中配置的每一个属性的值,映射到这个组件中向数据库的properties等等
Person

// @ConfigurationProperties和@PropertySource是可以一起用的
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = "classpath:person.properties")
public class Person {
    private String name;
    private Integer age;
    private Date birthday;
    private Boolean manager;
    // 读取的是classpath:person.properties的配置
    @Value("${person.email}")
    private String email;
    private List<Object> pets;
    private Map<String, Object> maps;
    private Car car;
}

person.properties

aaa@qq.com

运行的json***结果:

{"name":"张三","age":22,"birthday":640540800000,"manager":true,"email":"aaa@qq.com","pets":["dog","cat"],"maps":{"v1":"k1","v2":"k2"},"car":{"name":"法拉利","price":5000000.0}}

4. @ImportResource

在类路径下这样配置是不生效的userService不会初始化到IOC容器中,因为Spring Boot诞生的目的就是消除配置,
Spring Boot 配置文件
但是你非让配置文件生效也可以这样做

// 这个注解使applicationContext.xml生效
@ImportResource("classpath:applicationContext.xml")
@SpringBootApplication
public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    }

}

5. 定义和**指定profile

有这种场景就是测试环境和生产环境的application文件配置不一样,避免改来改去,可以定义Profile

Spring Boot 配置文件

5.1 定义application-dev.yml

server:
  port: 8080

person:
  name: 张三
  age: 22
  birthday: 1990/04/20
  manager: true
  pets:
    - dog
    - cat
  maps: {v1: k1,v2: k2}
  car:
    name: 法拉利
    price: 5000000

5.2 定义application-prod.yml

server:
  port: 8082

person:
  name: 李四
  age: 26
  birthday: 1991/04/20
  manager: false
  pets:
    - bird
    - cat
  maps: {v1: k1,v2: k2}
  car:
    name: BYD
    price: 50000

5.3 定义application.yml

spring:
  profiles:
    active: dev

dev测试结果:

{"name":"张三","age":22,"birthday":640540800000,"manager":true,"email":"aaa@qq.com","pets":["dog","cat"],"maps":{"v1":"k1","v2":"k2"},"car":{"name":"法拉利","price":5000000.0}}
spring:
  profiles:
    active: prod

prod测试结果:

{"name":"李四","age":26,"birthday":672076800000,"manager":false,"email":"aaa@qq.com","pets":["bird","cat"],"maps":{"v1":"k1","v2":"k2"},"car":{"name":"BYD","price":50000.0}}

5.4 properties定义Profile

properties定义Profile与yaml类似,在application.properties配置文件中指定 spring.profiles.active=dev

5.5 **指定profile其他方式

  • 在配置文件中指定 spring.profiles.active=dev
  • 命令行:java -jar Spring-Boot-Demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
  • 虚拟机参数:-Dspring.profiles.active=dev

6. 配置文件加载位置

  • –file:./config/ (项目路径下的config)

  • –file:./ (项目根路径)

  • –classpath:/config/ (类路径下的config)

  • –classpath:/ (类的根路径)

Spring Boot 配置文件

优先级由高到底,高优先级的配置会覆盖低优先级的相同配置;

SpringBoot会从这四个位置全部加载主配置文件,进行互补配置

启动参数spring.config.location指定applicaiton.yml

java -jar Spring-Boot-Demo-0.0.1-SNAPSHOT.jar --spring.config.location=F:/application.properties

7. 外部配置加载

SpringBoot也可以从以下位置加载配置; 优先级从高到低;高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置

  • 1.命令行参数
java -jar Spring-Boot-Demo-0.0.1-SNAPSHOT.jar --server.port=8086  --server.context-path=/demo
	所有的配置都可以在命令行上进行指定
	多个配置用空格分开; --配置项=值
  • 来自java:comp/env的JNDI属性

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

  • 操作系统环境变量

  • RandomValuePropertySource配置的random.*属性值

由jar包外向jar包内进行寻找,优先加载带profile

  • 6.jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件

  • 7.jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件

再来加载不带profile

  • 8.jar包外部的application.properties或application.yml(不带spring.profile)配置文件

  • 9.jar包内部的application.properties或application.yml(不带spring.profile)配置文件

  • aaa@qq.com注解类上的@PropertySource

  • 11.通过SpringApplication.setDefaultProperties指定的默认属性

所有支持的配置加载来源 :参考官方文档 --Externalized Configuration

8. 自动配置原理

配置文件能配置的属性参照 --Part X. Appendices

8.1 寻找代码入口:

  1. SpringBoot启动的时候加载主配置类@SpringBootApplication,开启了自动配置功能 @EnableAutoConfiguration
    Spring Boot 配置文件
  2. 父类的方法AutoConfigurationImportSelector#selectImports()
    Spring Boot 配置文件
  3. 调用本类的this.getCandidateConfigurations()
    Spring Boot 配置文件
  4. SpringFactoriesLoader#loadFactoryNames()
    Spring Boot 配置文件
  • 扫描所有jar包类路径下 META-INF/spring.factories
  • 把扫描到的这些文件的内容包装成Properties对象
  • 从Properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中
    Spring Boot 配置文件
  1. 所有EnableAutoConfiguration加入到了容器中的值
# Auto Configure
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.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,\
org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,\
org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,\
org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration

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

8.2 自动配置类的原理:

ServerPropertiesAutoConfiguration
Spring Boot 配置文件
Spring Boot 配置文件
所以我们配置server.port=8080,server.contextPath=/demo就封到这个Bean, 因为@ConfigurationProperties是松散绑定,server.contextPath可以写为server.context_path或server.context-path,但是spring推荐写为server.context-path。

9. 打印自动配置报告

我们怎么知道哪些自动配置类生效?我们可以通过启用 debug=true属性;来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效;
application.yml

debug: true

Positive matches:
Spring Boot 配置文件
Negative matches:
Spring Boot 配置文件
其他:
Spring Boot 配置文件

10. @Conditional派生注解

作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置里面的所有内容才生效;

@Conditional扩展注解 作用(判断是否满足当前指定条件)
@ConditionalOnJava 系统的java版本是否符合要求
@ConditionalOnBean 容器中存在指定Bean;
@ConditionalOnMissingBean 容器中不存在指定Bean;
@ConditionalOnExpression 满足SpEL表达式指定
@ConditionalOnClass 系统中有指定的类
@ConditionalOnMissingClass 系统中没有指定的类
@ConditionalOnSingleCandidate 容器中只有一个指定的Bean,或者这个Bean是首选Bean
@ConditionalOnProperty 系统中指定的属性是否有指定的值
@ConditionalOnResource 类路径下是否存在指定资源文件
@ConditionalOnWebApplication 当前是web环境
@ConditionalOnNotWebApplication 当前不是web环境
@ConditionalOnJndi JNDI存在指定项

说明:以上所有示例类未给出setter/getter

相关标签: Spring Boot