Search code examples
javaspring-bootyaml

Could not resolve YML @Value injected in a @Configuration class


As this answer seems to suggest, this should work fine

# application-dev.yml
gateway:
  publicEndpoints:
    - /api/v1/example,
    - /api/v1/another-example
@Configuration
@EnableWebFluxSecurity // does this annotation matter?
public class SecurityConfig {
    private final String[] publicEndpoints;

    public SecurityConfig(@Value("${gateway.publicEndpoints}") String[] publicEndpoints) {
        this.publicEndpoints = publicEndpoints; // a breakpoint here never gets hit
    }

    // ...

}

However, I get

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'gateway.publicEndpoints' in value "${gateway.publicEndpoints}"

I tried removing comma(s) in the yml file but get the same result

I also tried

@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {
    @Value("${gateway.publicEndpoints}")
    private String[] publicEndpoints;

Got the same exception

The profile is correct (dev):

The following 1 profile is active: "dev"

Salvatore Bernardo's proposal to use @ConfigurationProperties does help, however I'm still curious why I can't successfully use @Value in that code

Salvatore also hypothesized that it may be due to the yml format that @Value seems to not support (the doc does not corroborate that idea)

Another guy on SO had a similar problem, and it appears it was due to wrong identation (my identation is fine)

What is the cause of that behavior?

Spring Boot 3.1.4


Solution

  • for complex structure (List, Map) use ConfigurationProperties. I replicated here https://github.com/sbernardo/spring-issues-examples/tree/main/sof-questions-77691200 your problem and fixed using ConfigurationProperties

    This problem seems similar to Can't get Java see my custom YAML property in a Spring Boot app .

    @Value is good to use with simple value, for example String value.

    Hope this will help :)