9

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.

StanislavL
  • 56,971
  • 9
  • 68
  • 98
bench1ps
  • 173
  • 1
  • 1
  • 10
  • This post may help https://stackoverflow.com/questions/33369878/spring-boot-read-list-from-yaml-using-value-or-configurationproperties – Minh Kieu Jun 05 '17 at 12:45
  • did you include https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor – Daniel Jacob May 29 '20 at 11:38

2 Answers2

2

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

0

I got this error running a JUnit test on a SpringBoot app, what I was missing is the annotation @SpringBootTest

rvazquezglez
  • 2,284
  • 28
  • 40