My class:
package com.myCom.test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties( prefix = "sample.mail")
public class ConfigProperties {
@Value("${sample.mail.hostName}")
private String hostName;
private int port;
private String from;
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
}
My test:
package com.myCom.test;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(
classes = {
ConfigProperties.class
})
@SpringBootTest
public class ConfigPropertiesIT {
@Autowired
ConfigProperties properties;
@Test
public void testProperty() {
assertNotNull(properties);
assertNotNull(properties.getHostName());
assertNotNull(properties.getFrom());
}
}
My application.yaml
sample:
mail:
hostName: www.myCom.com
port: 8088
from: aUser
Why the hostName field worked, but not the from field? Adding @Value
annotation make a field work, and removing it makes a field not work. It almost seems as if the @ConfigurationProperties
annotation is not trying to bind the properties to the fields even though the name is matching. I suspect the @ContextConfiguration
may cause this binding to not happen, but I need help from somebody with deeper understanding.
Yes, that's likely the case. With such minimal configuration, nothing will have enabled configuration properties through
@EnableConfigurationProperties
. As such, configuration property binding will not happen as part of creating yourConfigProperties
component.You need to run your tests with some configuration that is annotated with
@EnableConfigurationProperties
.