I try to test a configuration file with a different profile using Spring configuration file name pattern.
Here is the structure of the Spring project:
src/main
java/foo/bar
config
RestClientConfig.java
ApiProperties.java
resources
application.yml
application-local.yml
application.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;
}
Rest template Configuration
@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();
}
}
When I run the following Unit test with Junit5, loads the properties from application.yml
instead of 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);
}
}
Based on the documentation yaml configuration specific to a profile is done differently. The convention followed here is for .properties
files.
Please refer the shared documentation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.