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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章