10

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.

2

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

Looks like the application.yml is not read. If unsure add a syntax error to it, e.g. a line containing just a colon. The application then must not start.

Check spelling of the filename and make sure the file is located in the working directory of the application. When using an IDE this usually means the file must be put next to the src folder.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.