Kevin
Kevin

Reputation: 1657

How do I read config values from application.yml in Spring 2.7.2

I've created a simple repo here that demonstrates my issue, just in case it helps anyone: https://github.com/kevinm416/spring-boot-config. I've tried various iterations of different Spring annotations I saw on different tutorials, but so far nothing has worked.

I have a very standard spring boot application:

@SpringBootApplication
@EnableConfigurationProperties({BaseConfig.class, FeedsConfig.class})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

And a configuration class:

@Component
@ConfigurationProperties(prefix = "feeds")
public class FeedsConfig {
    public List<String> urls;
    public String abc;
}

I've tried both application.properties and application.yml individually and at the same time, with contents like:

feeds:
  abc: def
  urls:
    - url1
    - url2
    - url3
base: level

When I @Autowire the config class into a controller, the values from the application config are not populated.

@RestController
public class HelloController {

    @Autowired
    private FeedsConfig feedsConfig;

    @Autowired
    private Environment environment;

    @RequestMapping("/hello")
    private String hello() {
        return "Hi " + feedsConfig.abc + ", " + feedsConfig.urls;
    }
}

I can see the values I want in the Environment under propertySources though! Why aren't my config classes being filled out?

Debugger showing environment


I changed FeedsConfig to this and it's working! Thank you Nicholas!

@ConstructorBinding
@ConfigurationProperties(prefix = "feeds")
public class FeedsConfig {
    public FeedsConfig(List<String> urls, String abc) {
        this.urls = urls;
        this.abc = abc;
    }
    public List<String> urls;
    public String abc;
}

Upvotes: 1

Views: 4056

Answers (2)

Roman
Roman

Reputation: 179

Looks like your configuration properties class is missing @ConfigurationPropertiesScan annotation. Also @Component and @EnableConfigurationProperties is no longer needed. Check out this tutorial, paragraph 3.1 https://www.baeldung.com/configuration-properties-in-spring-boot

@ConfigurationProperties(prefix = "feeds")
@EnableConfigurationProperties
public class FeedsConfig {
    public List<String> urls;
    public String abc;
}

Upvotes: 0

Nikolas
Nikolas

Reputation: 44368

Assuming the components are properly scanned, I see two issues:

  • FeedsConfig should not be annotated with @Component
  • FeedsConfig should have a full-args constructor and be annotated with @ConstructorBinding to wire the properties

This can be easily achieved using Lombok (I use the same set-up on my machine):

@Data
@ConfigurationProperties(prefix = "feeds")
@ConstructorBinding
@RequiredArgsConstructor
public class FeedsConfig {

    public List<String> urls;
    public String abc;
}

Upvotes: 1

Related Questions