Springboot-引入外部配置文件

SpringBoot——引入外部配置文件

博文地址:https://www.cnblogs.com/imchentiefeng/articles/springboot-inclue-config.html

git地址: SpringBoot——引入外部配置文件

背景

​ 在日常的开发中,我们往往需要一个项目使用多种组件,为了方便管理,我们希望能够让不同的组件使用不同的配置文件,尽可能的减少修改某个组件的配置文件时,对其他配置文件造成的影响。

使用

​ 为了实现不同的组件使用不同的配置文件,我们需要把每个配置文件引入到application.yml中,方法有如下两种:

  • 配置法:通过配置application.yml中的spring.profiles.include
  • 类加载法:Spring Framework有两个类加载YAML文件,YamlPropertiesFactoryBean和YamlMapFactoryBean,我们可以在程序启动的过程中,手动加载配置文件。

方法1:配置法:

1、创建附加的组件配置文件,如:application-common.yml,示例配置内容如下:

app:
  username: chentiefeng

2、在application.yml中引入application-common.yml配置文件

spring:
  profiles:
    include: common

3、创建一个Controller,测试使用application-common.yml中的配置

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Value("${app.username}")
    private String appUsername;

    @GetMapping("/test")
    public String hello() {
        return "Hello " + appUsername;
    }
}

4、浏览器访问:http://localhost:8080/test,可以看到Hello chentiefeng,证明成功取到了application-common.yml中的配置

方法2:类加载法

1、创建附加的组件配置文件,如:application-common.yml,示例配置内容如下:

app:
  username: chentiefeng

2、在spring 容器启动类或者配置类中,注册BeanPropertySourcesPlaceholderConfigurer

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;

/**
 * 自动加载的配置类
 *
 * @author chentiefeng
 * @date 2021/2/7 17:04
 */
@Configuration
public class TestAutoConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("application-common.yml"));
        configurer.setProperties(yaml.getObject());
        return configurer;
    }
}

3、创建一个Controller,测试使用application-common.yml中的配置

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Value("${app.username}")
    private String appUsername;

    @GetMapping("/test")
    public String hello() {
        return "Hello " + appUsername;
    }
}

4、浏览器访问:http://localhost:8080/test,可以看到Hello chentiefeng,证明成功取到了application-common.yml中的配置

posted @ 2021-02-07 22:48  编程Thinker  阅读(751)  评论(0)    收藏  举报