Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting null values when using ConfigurationProperties on Spring boot

Tags:

java

spring

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.

like image 909
bench1ps Avatar asked Jun 05 '17 12:06

bench1ps


1 Answers

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

like image 77
Alexander Nikolaev Avatar answered Oct 06 '22 05:10

Alexander Nikolaev