Spring Boot中的Properties的使用详解

2020-02-11 12:01:22于海丽

简介

本文我们将会讨怎么在Spring Boot中使用Properties。使用Properties有两种方式,一种是java代码的注解,一种是xml文件的配置。本文将会主要关注java代码的注解。

使用注解注册一个Properties文件

注册Properties文件我们可以使用@PropertySource 注解,该注解需要配合@Configuration 一起使用。

@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {
  //...
}

我们也可以使用placeholder来动态选择属性文件:

@PropertySource({ 
 "classpath:persistence-${envTarget:mysql}.properties"
})
@PropertySource也可以多次使用来定义多个属性文件:

@PropertySource("classpath:foo.properties")
@PropertySource("classpath:bar.properties")
public class PropertiesWithJavaConfig {
  //...
}

我们也可以使用@PropertySources来包含多个@PropertySource:

@PropertySources({
  @PropertySource("classpath:foo.properties"),
  @PropertySource("classpath:bar.properties")
})
public class PropertiesWithJavaConfig {
  //...
}

使用属性文件

最简单直接的使用办法就是使用@Value注解:

@Value( "${jdbc.url}" )
private String jdbcUrl;

我们也可以给属性添加默认值:

@Value( "${jdbc.url:aDefaultUrl}" )
private String jdbcUrl;

如果要在代码中使用属性值,我们可以从Environment API中获取:

@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));

Spring Boot中的属性文件

默认情况下Spring Boot 会读取application.properties文件作为默认的属性文件。当然,我们也可以在命令行提供一个不同的属性文件:

java -jar app.jar --spring.config.location=classpath:/another-location.properties

如果是在测试环境中,我们可以使用@TestPropertySource 来指定测试的属性文件:

@RunWith(SpringRunner.class)
@TestPropertySource("/foo.properties")
public class FilePropertyInjectionUnitTest {
 
  @Value("${foo}")
  private String foo;
 
  @Test
  public void whenFilePropertyProvided_thenProperlyInjected() {
    assertThat(foo).isEqualTo("bar");
  }
}

除了属性文件,我们也可以直接以key=value的形式:

@RunWith(SpringRunner.class)
@TestPropertySource(properties = {"foo=bar"})
public class PropertyInjectionUnitTest {
 
  @Value("${foo}")
  private String foo;
 
  @Test
  public void whenPropertyProvided_thenProperlyInjected() {
    assertThat(foo).isEqualTo("bar");
  }
}

使用@SpringBootTest,我们也可以使用类似的功能:

@RunWith(SpringRunner.class)
@SpringBootTest(properties = {"foo=bar"}, classes = SpringBootPropertiesTestApplication.class)
public class SpringBootPropertyInjectionIntegrationTest {
 
  @Value("${foo}")
  private String foo;
 
  @Test
  public void whenSpringBootPropertyProvided_thenProperlyInjected() {
    assertThat(foo).isEqualTo("bar");
  }
}