spring boot 加载自定义yml

个人在spring boot 开发中比较喜欢用yml文件,使用yml文件配置一些属性。自己在一个场景下需要加载自定义yml文件。

本人项目应用场景:自己的一个module引入了一个公有的module,里面已经有application.yml,避免重名,则将自己module的yml配置文件命名成其他名字,启动类加载的时候加载过来,然后再相应需要引用到配置文件属性的地方使用@Value获取。下面介绍两种比较常用的加载自定义yml文件方式:

1.ConfigurationProperties注解的locations属性在1.5.X已经取消,不能指定locations来加载yml文件;可以使用PropertySource注加载,详细见官方文档: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-yaml-shortcomings

2、PropertySourcesPlaceholderConfigurer 加载
      在启动类里注入一个Bean,用于加载自定义 yml配置文件

/**
     * 加载yml配置文件,根目录为resources
     * @return
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource[]{        
                new ClassPathResource("redis.yml")
        });
        pspc.setProperties(yaml.getObject());
        return pspc;
    }


 

猜你喜欢

转载自blog.csdn.net/qq_34147021/article/details/86575302