SRI HARSHA S V S
SRI HARSHA S V S

Reputation: 123

Springboot Unable to Read Yaml config

I am trying out a few things about YAML configuration, seems like I am missing something.

Below is my controller class and Yaml file.

HomeController.java

@Controller
@PropertySource("file:${user.dir}/config/webappdemo.yml")
public class HomeController {
    
    @Value("${app.message}")
    private String appMessage;

    @GetMapping("/home")
    @ResponseBody
    public String homePage() {
        return this.appMessage;
    }
}

webappdemo.yml

app:
   message: hello

My application failing to start, with the below exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'homeController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'app.message' in value "${app.message}"
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:405) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1413) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.9.jar:5.3.9]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.9.jar:5.3.9]

From the error message I can feel, because of some reason, It's not able to find that property If I modify the property file as below, Its working, Please help me identify the issue:

webappdemo.yml

app.message=hello

Upvotes: 3

Views: 8143

Answers (1)

Joker
Joker

Reputation: 2463

PropertySource doesn't support .yml, you need to use .properties file in this case.

"YAML files cannot be loaded by using the @PropertySource or @TestPropertySource annotations. So, in the case that you need to load values that way, you need to use a properties file"

It From the official docs at 2.5.1. Mapping YAML to Properties

You might find solutions/workarounds in Spring @PropertySource using YAML

Upvotes: 5

Related Questions