springboot 加載自定義yml文件


Springboot加載自定義yml文件配置的方法

  1. ConfigurationProperties注解的locations屬性在1.5.X以后沒有了,不能指定locations來加載yml文件

    image-20200724155412600

  2. PropertySource注解不支持yml文件加載,詳細見官方文檔:

image-20200724155336975

  1. Spring Framework有兩個類加載YAML文件,YamlPropertiesFactoryBean和YamlMapFactoryBean

image-20200724155457932

  1. 可以通過PropertySourcePlaceholderConfigurer來加載yml文件,暴露yml文件到spring environment
/**
 * @author WGR
 * @create 2020/7/24 -- 15:31
 */
@Configuration
public class SpringBootConfigura {
    // 加載YML格式自定義配置文件
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("config.yml"));//File引入
        configurer.setProperties(yaml.getObject());
        return configurer;
    }
}

配置文件:

my:
  servers:
    - dev.example.com
    - another.example.com
    - ${random.value}
  1. 測試
@Controller
public class SpringBootTest {

    @Autowired
    Config config;

    @GetMapping("/testConfig")
    @ResponseBody
    public String testConfig(){
        return config.getServers().toString();
    }
}

image-20200724155645621


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM