(3)Spring Boot 配置文件、加载顺序、配置原理

文章内容

  • SpringBoot配置文件的基本使用;
  • yaml配置文件优先级问题讲解;
  • yaml配置文件目录及比较说明;
  • 自定义配置属性;
  • @ConfigurationProperties与@Value两种注解对比;
  • idea自定义yaml配置提示
  • 加载外部配置;
  • 装配配置文件(properties,yaml);
  • 引入xml配置文件。

一、SpringBoot配置文件的基本使用

(1)SpringBoot使用一个全局的配置文件,配置文件名是固定的;

  • application.properties
  • application.yml
  • YAML基本语法
       – 使用缩进表示层级关系
       – 缩进时不允许使用Tab键,只允许使用空格
       – 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
       – 大小写敏感
  • YAML 支持的三种数据结构
     – 对象:键值对的集合
     – 数组:一组按次序排列的值
     – 字面量:单个的、不可再分的值

(2)实践结论:在同一目录下,properties配置优先级 > YAML配置优先级。

                           所以我们在jar包启动时带上properties写法的配置可以覆盖配置

(3)配置文件目录:

     SpringBoot配置文件可以放置在多种路径下,不同路径下的配置优先级有所不同。可放置目录(优先级从高到低)

  1. file:./config/ (当前项目路径config目录下);
  2. file:./ (当前项目路径下);
  3. classpath:/config/ (类路径config目录下);
  4. classpath:/ (类路径config下). 

优先级由高到底,高优先级的配置会覆盖低优先级的配置;SpringBoot会从这四个位置全部加载配置文件并互补配置

  •   依赖路径的类:ConfigFileApplicationListener

    

      DEFAULT_SEARCH_LOCATIONS属性设置了加载的目录;getSearchLocations()方法中去逗号解析成Set,其中内部类Loader负责这一配置文件的加载过程,包括加载profile指定环境的配置,以application+’-’+name格式的拼接加载

private Set<String> getSearchLocations() {
      if (this.environment.containsProperty("spring.config.location")) {
         return this.getSearchLocations("spring.config.location");
        } else {
                Set<String> locations = 
           this.getSearchLocations("spring.config.additional-location");
                locations.addAll(
                   this.asResolvedSet(ConfigFileApplicationListener.this.searchLocations, 
                  "classpath:/,classpath:/config/,file:./,file:./config/"));
                return locations;
            }
        }

  添加到List后进行集合顺序反转:

private Set<String> asResolvedSet(String value, String fallback) {
            List<String> list = Arrays.asList(StringUtils.trimArrayElements
                  (StringUtils.commaDelimitedListToStringArray(value != null ? 
                       this.environment.resolvePlaceholders(value) : fallback)));
            Collections.reverse(list);
            return new LinkedHashSet(list);
        }

 综上所述:

   接下来还是以端口配置为例

  1. 在resources/目录下配置文件设置端口为8888;
  2. 在resources/config目录下配置文件设置端口为9999;
  3. 在项目路径下配置文件设置端口为6666;
  4. 在项目路径config目录下配置文件设置端口为7777;

               å¨è¿éæå¥å¾çæè¿°

最终运行结果:

  

通过控制变量法得以论证
其优先级由高到底,高优先级的配置会覆盖低优先级的配置

二、 静态资源访问规则、自定义静态文件配置方法

三、配置文件绑定值到bean的方式

(1)在Spring Boot中使用 @ConfigurationProperties 注解+@Component

@Component
@ConfigurationProperties(locations = "classpath:mail.properties", 
                                     ignoreUnknownFields = false, prefix = "mail")
public class MailProperties {
    private String host;
    private int port;
    private String from;
    private String username;
    private String password;
    private Smtp smtp;
}

(2)@Bean+@ConfigurationProperties  进行进行绑定

    @Bean
    @ConfigurationProperties(locations = "classpath:mail.properties", prefix = "mail")
    public MailProperties mailProperties(){
        MailProperties mp = new MailProperties();
        System.out.println("zheli " + mp);
        return mp;

    }

  (3)@ConfigurationProperties + @EnableConfigurationProperties  ,然后用 Spring的@Autowire来注入 mail configuration bean:

@ConfigurationProperties(locations = "classpath:mail.properties", 
                                ignoreUnknownFields = false, prefix = "mail")
public class MailProperties {
    private String host;
    private int port;
    private String from;
    private String username;
    private String password;
    private Smtp smtp;
}

方式(3)中最后需要@EnableConfigurationProperties(Person.class) 可以使得 @ConfigurationProperties: 生效

然后在启动类中,如下配置   @EnableConfigurationProperties   ,在使用的地方再@Autowired注入

@SpringBootApplication
@EnableConfigurationProperties(MailProperties.class)
public class TestProperty1 {

    @Autowired
    private MailProperties mailProperties;

}

四、@Value获取值和@ConfigurationProperties获取值比较

注意:配置文件yml还是properties他们都能获取到值;(复杂类型比如maps、lists等)

  • 如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value;
  • 如果说,我们专门编写了一个javaBean来和配置文件进行映射,我们就直接使用@ConfigurationProperties;

配置文件加入数据校验:

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
     * <bean/>
     */

   //lastName必须是邮箱格式
    @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;

    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

六、加载指定的配置文件

(1)@PropertySource&@ImportResource&@Bean

  • @PropertySource:加载指定的配置文件;
/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
 *      prefix = "person":配置文件中哪个下面的所有属性进行一一映射
 *
 * 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
 *  @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;
 *
 */
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
//@Validated
public class Person {

    /**
     * <bean class="Person">
     *      <property name="lastName" value="字面量/${key}从环境变量、配置文件中获取值/#{SpEL}"></property>
     * <bean/>
     */

   //lastName必须是邮箱格式
   // @Email
    //@Value("${person.last-name}")
    private String lastName;
    //@Value("#{11*2}")
    private Integer age;
    //@Value("true")
    private Boolean boss;
  • @ImportResource:导入Spring的配置文件,让配置文件里面的内容生效;

    Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;

    想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上

@ImportResource(locations = {"classpath:beans.xml"})
导入Spring的配置文件让其生效

来编写Spring的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">


    <bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>

SpringBoot推荐给容器中添加组件的方式;推荐使用全注解的方式

1、配置类@Configuration------>Spring配置文件

2、使用@Bean给容器中添加组件

/**
 * @Configuration:指明当前类是一个配置类;就是来替代之前的Spring配置文件
 *
 * 在配置文件中用<bean><bean/>标签添加组件
 *
 */
@Configuration
public class MyAppConfig {

    //将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService02(){
        System.out.println("配置类@Bean给容器中添加组件了...");
        return new HelloService();
    }
}
发布了108 篇原创文章 · 获赞 58 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_41893274/article/details/104712405