美文网首页
12-SpringBoot

12-SpringBoot

作者: XAbo | 来源:发表于2022-03-29 21:47 被阅读0次

一、基础配置

1.1 配置优先级

Spring Boot启动会扫描以下位置的application.properties或者application.yml文件作为Spring Boot的默认配置文件

file:./config/             ## 优先级最高
file:./                    ## 优先级高
classpath:/config/         ## 优先级中
classpath:/                ## 优先级低

通过spring.config.location来改变默认的配置文件位置。

java -jar xxx.jar --spring.config.location=D:/myconfig.properties

通过spring.config.name来改变默认的配置文件名称。

java -jar xxx.jar --spring.config.name=myconfig

SpringBoot也可以从以下位置加载配置;优先级从高到低:

配置文件优先级

1.2 读取配置文件

  • 单个数据:获取一下配置文件中的某项值,使用@Value
  • 全部数据:使用Environment+@AutoWired获取全部配置文件的数据。
  • 部分数据:用javaBean来和配置文件进行映射,使用@ConfigurationProperties。第三方的bean也可以使用该注解进行属性注入。且支持松散绑定。
/**
 @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定; 
 prefix = "person" :配置文件中那个下面的所有属性进行一一映射
 只有这个组件是容器中的组件,才能容器提供的ConfigurationProperties功能;
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
读取配置文件

@ConfigurationProperties是给单个对象进行属性绑定,该方式较松散。

@ConfigurationProperties

@EnableConfigurationProperties指定哪些对象的属性需要从配置文件中绑定,方便统一管理。使用该方式则不需要在目标类上添加@Component。但是@EnableConfigurationProperties不能给第三方类属性赋值。

@EnableConfigurationProperties

1.3 多环境多文件的配置

1-在springboot中配置多环境

多环境-单文件:不支持properties配置文件 多环境-多文件:支持properties配置文件 多环境-多文件:不支持properties配置文件

2-在maven中配置boot多环境

当maven中配置了多环境的时候,maven和springboot两套环境配置会存在冲突,所以实际开发中以maven读取springboot中的环境配置居多。

1-pom中配置 2-springboot应用maven配置

二、Boot重点内容

2.1Bean的加载控制

bean的创建方式
  • ImportSelector的接口方式,根据Bean的元数据信息来,控制是否加载。

    ImportSelector
  • ImportBeanDefinitionRegistrar接口, 自定义BeanDefinition注册到spring容器中。

ImportBeanDefinitionRegistrar
  • BeanDefinitionRegistryPostProcessor接口,在Bean加载后,决定Bean的最终加载。
    BeanDefinitionRegistryPostProcessor

相关文章

  • 12-SpringBoot

    一、基础配置 1.1 配置优先级 Spring Boot启动会扫描以下位置的application.propert...

网友评论

      本文标题:12-SpringBoot

      本文链接:https://www.haomeiwen.com/subject/nambjrtx.html