springBoot加载配置文件

发布于:2024-04-28 ⋅ 阅读:(29) ⋅ 点赞:(0)

1. 说明

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

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

2. 获取配置信息

2.1 @Value

(1) 说明

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

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

(2)示例

    @Value("${key:defaultValue}")
    private String demoKey;

2.2 @ConfigurationProperties

(1) 说明

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

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

(2)示例

@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)示例

    @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)示例

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

3.2 PropertySourcesPlaceholderConfigurer

(1) 说明

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

(2)示例

    /**
     * 加载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)示例

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)示例

// 加载 /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)示例

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

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

   @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}获取其他配置数据


网站公告

今日签到

点亮在社区的每一天
去签到