从配置文件中获取属性应该是SpringBoot开发中最为常用的功能之一,但就是这么常用的功能,仍然有很多开发者抓狂~今天带大家简单回顾一下这六种的使用方式:

一、Environment

注入Environment类调用其方法getProperty(属性key)即可

@Slf4j
@SpringBootTest
public class EnvironmentTest {

    @Resource
    private Environment env;

    @Test
    public void var1Test() {
        String var1 = env.getProperty("env.var1");
        log.info("Environment获取的配置内容:{}", var1);
    }
}

二、@Value 注解

只要在变量上加注解 @Value("${env.var1}")就可以了,@Value 注解会自动将配置文件中的env.var1属性值注入到var1字段中。

@Slf4j
@SpringBootTest
public class EnvVariablesTest {

    @Value("${env.var1}")
    private String var1;
    
    @Test
    public void var1Test(){
        log.info("配置文件属性: {}",var1);
    }
}

三、@ConfigurationProperties 注解

在 application.yml 配置文件中添加配置项:

env:
  var1: 变量值1
  var2: 变量值2

创建一个 MyConf 类用于承载所有前缀为env的配置属性。

@Data
@Configuration
@ConfigurationProperties(prefix = "env")
public class MyConf {

    private String var1;
    
    private String var2;
}

在需要使用var1、var2属性值的地方,将 MyConf 对象注入到依赖对象中即可。

@Slf4j
@SpringBootTest
public class ConfTest {

    @Resource
    private MyConf myConf;

    @Test
    public void myConfTest() {
        log.info("@ConfigurationProperties注解获取的配置内容:{}", JSON.toJSONString(myConf));
    }
}

四、@PropertySources 注解

在 src/main/resources/ 目录下创建自定义配置文件 important.properties,增加两个属性。

env.var1=变量值1
env.var2=变量值2

在需要使用自定义配置文件的类上添加 @PropertySources 注解,注解 value属性中指定自定义配置文件的路径,可以指定多个路径,用逗号隔开。

@Data
@Configuration
@PropertySources({
        @PropertySource(value = "classpath:important.properties", encoding = "utf-8"),
        @PropertySource(value = "classpath:important.properties",encoding = "utf-8")
})
public class PropertySourcesConf {

    @Value("${env.var1}")
    private String var1;

    @Value("${env.var2}")
    private String var2;
}

五、YamlPropertiesFactoryBean 加载 YAML 文件

@Configuration
public class MyYamlConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer yamlConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("test.yml"));
        configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
        return configurer;
    }
}

可以通过 @Value 注解或 Environment.getProperty() 方法来获取其中定义的属性值。

@Slf4j
@SpringBootTest
public class YamlTest {

    @Value("${env.var3}")
    private String var3;

    @Test
    public void  myYamlTest() {
        log.info("Yaml获取配置内容:{}", var3);
    }
}

六、JAVA原生读取

@Slf4j
@SpringBootTest
public class CustomTest {

    @Test
    public void customTest() {
        Properties props = new Properties();
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(
                    this.getClass().getClassLoader().getResourceAsStream("test.properties"),
                    StandardCharsets.UTF_8);
            props.load(inputStreamReader);
        } catch (IOException e1) {
            System.out.println(e1);
        }
        log.info("Properties Name:" + props.getProperty("env.appName"));
    }
}

10-30 11:36