I'm new to the Java world and Spring boot, and I'm trying to access some configuration values located in a YAML file through the ConfigurationProperties
annotation.
But whenever I try to access a configuration value anywhere in a service, I get a null value.
Here's the application.yml
file:
my_config:
test: "plop"
Here's the ValidationProperties
configuration class:
@Configuration
@ConfigurationProperties(prefix = "my_config")
public class ValidationProperties {
@NotNull
private String test;
public void setTest(String test) {
this.test = test;
}
public String getTest() {
return this.test;
}
}
A validator service that uses it:
@Service
public class MyValidator implements ConstraintValidator<MyConstraint, MyEntity> {
@Autowired
private ValidationProperties validationProperties;
@Value("${my_config.test}")
private String test;
@Override
public boolean isValid(MyEntity entity, ConstraintValidatorContext context) {
System.out.println(this.test); // null value, why?
}
}
I also added the @EnableConfigurationProperties
annotation in my main class.
I'm not sure which annotation is supposed to do what, but I'm obviously missing something here. Also, if I try to access the value from the getter of the configuration file, I get an exception:
System.out.println(this.validationProperties.getTest());
will get me HV000028: Unexpected exception during isValid call.
Try adding @EnableConfigurationProperties(ValidationProperties.class)
on your main application class or any other @Configuration
class.
Also putting @Component
annotation on ValidationProperties should work.
No need to inject value via @Value
annotation, just access it via getter of injected validationProperties
object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With