SpringBoot 之加载配置文件

application

spring.config.name 指定配置文件名称,默认:application(一般不建议修改)源码:StandardConfigDataLocationResolver
spring.config.location 指定配置文件路径。源码:ConfigDataEnvironment

java -jar  boot.jar --spring.config.location=./config/

bootstrap

bootstrap 属于 Spring Cloud 环境,需要引入 Spring Cloud 依赖才能使用。
bootstrap 由父 ApplicationContext 加载,比 application 优先加载。
bootstrap 里面的参数不能被覆盖。

配置绑定

所有已加载到 Spring 环境的配置都可以通过注入 Environment 环境 Bean 获取到。

@Autowired
private Environment env;
// 获取参数
String getProperty(String key);

@Value("${property}") 注解用类成员变量绑定配置参数。

为了让 SpringBoot 更好的生成配置元数据文件,我们需要添加如下依赖(该依赖可以不添加,但是在 IDEA 和 STS 中不会有属性提示),该依赖只会在编译时调用,所以不会对生产造成影响。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

使用@PropertySource加载properties配置文件

只能加载 .properties 配置文件,比如绑定资源目录下的 config/db-config.properties 配置参数。

@Data
@Component
@PropertySource(value = {"config/db-config.properties"})
public class DbProperties {
    @Value("${db.username}")
    private String username;
}

使用Environment加载配置文件

在运行SpringApplication之前加载任意配置文件到Environment环境中。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.util.Objects;
import java.util.Properties;

// 自定义环境处理,在运行SpringApplication之前加载任意配置文件到Environment环境中
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {

    //Properties对象
    private final Properties properties = new Properties();

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        //自定义配置文件
        String[] profiles = {
                "db.yml"
        };

        //循环添加
        for (String profile : profiles) {
            //从classpath路径下面查找文件
            Resource resource = new ClassPathResource(profile);
            //加载成PropertySource对象,并添加到Environment环境中
            environment.getPropertySources().addLast(loadProfiles(resource));
        }
    }

    //加载单个配置文件
    private PropertySource<?> loadProfiles(Resource resource) {
        if (!resource.exists()) {
            throw new IllegalArgumentException("资源" + resource + "不存在");
        }
        try {
            //从输入流中加载一个Properties对象
            properties.load(resource.getInputStream());
            return new PropertiesPropertySource(Objects.requireNonNull(resource.getFilename()), properties);
        } catch (IOException ex) {
            throw new IllegalStateException("加载配置文件失败" + resource, ex);
        }
    }
}

并且在META-INF/spring.factories中:

#启用我们的自定义环境处理类
org.springframework.boot.env.EnvironmentPostProcessor=com.boot.demo.MyEnvironmentPostProcessor

配置文件:db.yml

db.address: nj

使用PropertySourcePlaceholderConfigurer加载配置文件

1、@PropertySource 注解只支持*.properties文件,不支持yml文件。
2、Spring Framework有两个类加载YAML文件,YamlPropertiesFactoryBeanYamlMapFactoryBean
3、可以通过PropertySourcePlaceholderConfigurer来加载yml文件,暴露yml文件到spring environment

// 加载YML格式自定义配置文件
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
	PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
	YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
	yaml.setResources(new FileSystemResource("config.yml"));//File引入
	yaml.setResources(new ClassPathResource("test.yml"));//class引入
	configurer.setProperties(yaml.getObject());
	return configurer;
}

属性值注入Bean的两种方式

通过@Value引入属性值注入Bean

@Value("${test.username}")
private String username;

通过@ConfigurationProperties;(调用属性的setter方法进行注入)

yyqq:
  name: James
  users:
    - Jom
    - Lucy
  params:
    tel: 18800008888
    address: China
  security:
    security-key: 123321
    security-code: 666666
/**
 *
 * @ConfigurationProperties 表示 告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
 * prefix = "myuser" 表示 将配置文件中key为user的下面所有的属性与本类属性进行一一映射注入值,如果配置文件中
 * 不存在"myuser"的key,则不会为POJO注入值,属性值仍然为默认值
 * <p/>
 * @ConfigurationProperties (prefix = "myuser") 默认从全局配置文件中获取值然后进行注入
 * @Component 将本来标识为一个Spring 组件,因为只有是容器中的组件,容器才会为@ConfigurationProperties提供此注入功能
 */
@Data
@Component
@ConfigurationProperties(prefix = "yyqq")
public class JavastackProperties {
    private String name;
    private List<String> users;
    private Map<String, String> params;
    private Security security;
}
@Data
class Security {
    private String securityKey;
    private String securityCode;
}

命令行参数

--开头的参数。java -jar demo.jar --server.port=9090
命令行参数的优先级高于配置文件。
在这里插入图片描述

Environment详解

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot可以通过多种方式加载配置文件,包括: 1. application.properties/application.yml文件:Spring Boot会自动加载classpath下的这两个文件,可以在其中定义应用程序的配置属性。 2. @PropertySource注解:可以通过该注解指定要加载配置文件,例如: @SpringBootApplication @PropertySource("classpath:myconfig.properties") public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } 3. Environment接口:可以通过该接口获取配置属性的值,例如: @Autowired private Environment env; String value = env.getProperty("my.property"); 4. 自定义配置文件:可以通过实现org.springframework.boot.env.PropertySourceLoader接口来加载自定义的配置文件,例如: public class MyPropertySourceLoader implements PropertySourceLoader { @Override public String[] getFileExtensions() { return new String[] { "myconfig" }; } @Override public PropertySource<?> load(String name, Resource resource, String profile) throws IOException { Properties props = new Properties(); props.load(resource.getInputStream()); return new PropertiesPropertySource(name, props); } } 然后在application.properties/application.yml中添加以下配置: spring.profiles.active=myprofile spring.config.name=myconfig spring.config.location=classpath:/,classpath:/config/ 这样就可以在classpath:/或classpath:/config/目录下加载myconfig.myprofile文件了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值