我尝试使用Spring配置文件名称模式测试具有不同配置文件的配置文件。
以下是 Spring 项目的结构:
src/main
java/foo/bar
config
RestClientConfig.java
ApiProperties.java
resources
application.yml
application-local.yml
应用程序.yml
api:
authentication-hash: fds456f4ds6f
rest-api-uri: https://example.org/api
application-local.yml
api:
authentication-hash: xxxxxxxxx
rest-api-uri: https://localhost:8081/api
ApiProperties.java
@Configuration
@ConfigurationProperties(prefix = "boond")
@Data
public class BoondProperties {
@ToString.Exclude // confidentiel
private String authenticationHash;
private URI restApiUri;
}
休息模板配置
@Configuration
public class RestClientConfig {
private final ApiProperties apiProperties;
public RestClientConfig(apiProperties apiProperties) {
this.apiProperties = apiProperties;
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
builder.defaultHeader("Authorization", "Basic " +
apiProperties.getAuthenticationHash());
builder.uriTemplateHandler(
new DefaultUriBuilderFactory(apiProperties.getRestApiUri().toString()));
return builder.build();
}
}
当我使用 Junit5 运行以下单元测试时,从application.yml
加载属性而不是application-local.yml
@SpringBootTest
@ActiveProfiles("local")
class RestClientConfigTest {
@Autowired
RestClientConfig restClientConfig;
@Autowired
RestTemplateBuilder restTemplateBuilder;
@Test
void rest_client_should_be_able_to_contact_api() {
RestTemplate apiRestTemplate = restClientConfig.restTemplate(restTemplateBuilder);
ResponseEntity<String> dictionary = apiRestTemplate.getForEntity("/api/dictionary", String.class);
assertEquals("OK", dictionary);
}
}
根据文档,特定于配置文件的 yaml 配置以不同的方式完成。此处遵循的约定适用于.properties
文件。
请参考共享文档