springboot家在配置问题

配置文件位置

1、默认位置

springboot默认配置文件名称为application.properties,SpringApplication将从一下位置将配置文件加载到spring Environment中

  1. 当前目录下的/config子目录
  2. 当前目录
  3. 一个classpath下的/config子目录
  4. classpath根路径

这个顺序按优先级进行加载,如果有多个同名的application.properties文件,最上面的覆盖最下面的。

2、自定义位置

如果需要自定义文件名或者位置,则在启动springboot时传入参数spring.config.location

3、动态加载外部配置

  1. 实现EnvironmentPostProcessor接口,并配置到容器当中
    @Component
    public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
        @Override
        public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
            try (InputStream stream = new FileInputStream("d:\\jdbc.properties")){
                Properties properties = new Properties();
                properties.load(stream);
                PropertiesPropertySource source = new PropertiesPropertySource("jdbc",properties);
                configurableEnvironment.getPropertySources().addLast(source);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

     

  2. 在classpath下的META-INF下加一个spring.factories文件,在文件中配置
    org.springframework.boot.env.EnvironmentPostProcessor=com.xxx.MyEnvironmentPostProcessor

     

这样再启动springboot是,springboot会根据spring.factories文件中的配置找到EnvironmentPostProcessor的实现类,执行

postProcessEnvironment方法,将配置文件加载到系统当中。

将配置文件中的数据加载到类中

  1. @Component和@Value("${"xxx"}")

    @Component
    public class Configurations {
        
        @Value("${test.name}")
        private String name;
    
        @Value("${test.age}")
        private String age;
    
        @Value("${test.tel}")
        private Long tel;
    
        // getter and setter
    }

     

@ConfigurationProperties(prefix = "test")

@Component
@ConfigurationProperties(prefix = "test")
public class Configuration {

    private String name;

    private String age;

    private Long tel;

    // setter getter
}

将配置文件中已test开头的这几个属性加载到类中,当然还可以制定家在哪个配置文件

@ConfigurationProperties(prefix = "test", locations = "classpath:xxxx.properties")

根据环境不同加载不同配置,家在多个配置文件

  1. profiles
    1. 不同环境下的配置文件名称application-{profile}.properties
      1. application-dev.properties
      2. application-test.properties
      3. application.pro.properties
    2. 在默认配置文件中配置spring.profiles.active={profile},就可以加载不同的配置文件了,比如spring.profiles.active=dev就是加载application-dev.properties文件。
  2. 通过启动参数加载不同的配置文件--spring.profiles.active=test
  3. 加再多个配置文件:spring.profiles.active=dev,test

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值