springBoot加载配置文件

1. 说明

Spring Boot会自动加载application.propertiesapplication.yml,所放置的位置如下表,所有位置的文件都会被加载(互补配置),高优先级配置内容会覆盖低优先级配置内容。

|------------------------|-------|
| 位置 | 优先级 |
| 项目根目录config文件夹下 | 优先级最高 |
| 项目根目录下 | 优先级第二 |
| resources目录中config文件夹下 | 优先级第三 |
| resources目录下 | 优先级最低 |
[自动加载配置文件的目录及优先级]

2. 获取配置信息

2.1 @Value

(1) 说明

可直接用@Value注解获取已加载指定key的配置数据。

可通过 :defaultValue 设置默认值,不设置默认值时 key 不存在时会抛出异常

(2)示例

java 复制代码
    @Value("${key:defaultValue}")
    private String demoKey;

2.2 @ConfigurationProperties

(1) 说明

将指定前缀的配置封装到实体类中。有如下属性:

|---------------------|---------------------------------------|
| 属性 | 说明 |
| value、prefix | 配置前缀 |
| ignoreInvalidFields | 默认是false,当绑定时候出现错误是否要忽略,这种错误一般是类型转换错误 |
| ignoreUnknownFields | 默认是true,会忽略掉配置文件里未绑定到实体里的配置 |
[ConfigurationProperties属性]

(2)示例

java 复制代码
@Component
@ConfigurationProperties(prefix="demo")
public class DemoProperties {
    // 获取demo.a1
    private String a1;
    // 获取demo.a2
    private String a2;
    
    //todo set/get方法
}

2.3 Environment

(1) 说明

是一个提供访问环境变量的类**。**常用方法有:

|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------|
| 方法 | 说明 |
| getProperty(String key) getProperty(String key, String defaultValue) getProperty(String key, Class<T> targetType) getProperty(String key, Class<T> targetType, T defaultValue) | 获取指定key的配置信息 可设置默认值或数据类型 |
| getRequiredProperty(String key) getRequiredProperty(String key, Class<T> targetType) | 获取指定key的必要配置信息,不存在会抛异常。 |
| resolvePlaceholders(String text) | 通过占位符获取配置信息。例如:${key} |
| resolveRequiredPlaceholders(String text) | 通过占位符获取必要配置信息,不存在会抛异常。 |
| getActiveProfiles() | 获取当前的环境配置 |
| getDefaultProfiles() | 获取默认的环境配置 |
| acceptsProfiles(Profiles profiles) | 判断是否激活指定环境配置 |

(2)示例

java 复制代码
    @Autowired
    Environment environment;
    @Test
    void contextLoads2() throws Exception {
        System.out.println(environment.getProperty("demo.k1"));
    }

3. 引入外部配置文件

3.1 @PropertySource

(1) 说明

用于指定资源文件读取的位置,它不仅能读取properties文件,也能读取xml文件,并且还可通过YAML解析器,配合自定义PropertySourceFactory实现解析YAML文件。

|------------------------|----------------------------------------|
| 属性 | 说明 |
| name | 该PropertySource的名字,如果不指定会用文件名按照一定的方式生成 |
| value | 指定扫描文件的路径,可以配置多个 |
| ignoreResourceNotFound | 当资源不存在时,是否忽略,默认不忽略,也就是会报错。 |
| encoding | 指定文件编码 |
| factory | 指定文件解析工厂,可用于解析不同类型的配置文件,如 yml |

(2)示例

java 复制代码
@Component
@PropertySource(value = "classpath:demo.properties",encoding = "utf-8")
public class Config {
}

3.2 PropertySourcesPlaceholderConfigurer

(1) 说明

读取外部配置文件,并将配置文件中的属性值注入到应用程序中。

(2)示例

java 复制代码
    /**
     * 加载yml配置文件
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer yamlConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("demo.yml"));
        configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
        return configurer;
    }
    /**
     * 加载properties配置文件
     */
    @Bean
    public PropertySourcesPlaceholderConfigurer propertiesConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setLocations(new ClassPathResource("demo.properties"));
        return configurer;
    }

3.3 直接加载并获取配置信息

(1) 说明

Properties是一个Map体系集合类,继承于Hashtable。主要用于读取Java的properties配置文件。

注:也可使用其他类库直接读取配置文件。

(2)示例

java 复制代码
InputStream ips = new FileInputStream("config.properties");
Properties props = new Properties();
props.load(ips);
ips.close();
String value= props.getProperty("key");

3.4 命令行参数

(1) 说明

可以通过 --spring.config.location参数来指定配置文件的位置。

可以通过 --spring.config.name 参数指定配置文件名称。

注:也可 使用 --app.key=value 修改配置文件中的配置

(2)示例

bash 复制代码
// 加载 /path/config/ 下的myconfig.properties或myconfig.yml配置文件
java -jar app.jar --spring.config.location=file:/path/config/  --spring.config.name=myconfig

4. 分环境加载配置文件

4.1 默认加载的配置文件

(1) 说明

可通过 application-{profile}.properties 或application-{profile}.yml的方式配置多个配置文件。

注:application.properties 或application.yml可配置公共配置数据。

4.2 @Profile

(1) 说明

常和@Component、@Configuration、@Bean注解一块使用,用于标明需要spring管理类是否需要管理的环境。

注:只有配置了spring.profiles.active 或 spring.profiles.default 时@Profile才会生效。

(2)示例

java 复制代码
//Config类只有在dev环境时由spring管理
//可通过配置多个不同环境的相同类来做到分环境加载配置
@Component
@Profile("dev")
public class Config {
    //DataSource类只有在test环境时由spring管理
    @Bean
    @Profile("test")
    public DataSource getTestDataSource () {
        return null;
    }
}

4.3 引入外部配置文件时自定义不同环境的文件名

java 复制代码
   @Bean
    public PropertySourcesPlaceholderConfigurer configurer1(Environment environment) {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        String[] activeProfiles = environment.getActiveProfiles();
        if (activeProfiles != null && activeProfiles.length > 0) {
            YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            ClassPathResource[] resources=new ClassPathResource[activeProfiles.length];
            for (int i = 0; i < activeProfiles.length; i++) {
                resources[i]=new ClassPathResource("demo-" + activeProfiles[i] + ".yml");
            }
            yaml.setResources(resources);
            configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
        }
        return configurer;
    }
    @Bean
    public PropertySourcesPlaceholderConfigurer configurer2(Environment environment) {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        String[] activeProfiles = environment.getActiveProfiles();
        if (activeProfiles != null && activeProfiles.length > 0) {
            for (int i = 0; i < activeProfiles.length; i++) {
                configurer.setLocations(new ClassPathResource("demo-" + activeProfiles[i] + ".properties"));
            }
        }
        return configurer;
    }

5. 配置文件常用语法

(1)可使用${key}获取其他配置数据

相关推荐
救救孩子把13 分钟前
深入理解 Java 对象的内存布局
java
落落落sss16 分钟前
MybatisPlus
android·java·开发语言·spring·tomcat·rabbitmq·mybatis
万物皆字节21 分钟前
maven指定模块快速打包idea插件Quick Maven Package
java
夜雨翦春韭28 分钟前
【代码随想录Day30】贪心算法Part04
java·数据结构·算法·leetcode·贪心算法
我行我素,向往自由35 分钟前
速成java记录(上)
java·速成
一直学习永不止步40 分钟前
LeetCode题练习与总结:H 指数--274
java·数据结构·算法·leetcode·数组·排序·计数排序
邵泽明41 分钟前
面试知识储备-多线程
java·面试·职场和发展
程序员是干活的1 小时前
私家车开车回家过节会发生什么事情
java·开发语言·软件构建·1024程序员节
煸橙干儿~~1 小时前
分析JS Crash(进程崩溃)
java·前端·javascript
2401_854391081 小时前
Spring Boot大学生就业招聘系统的开发与部署
java·spring boot·后端