Issue
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
Solution
PropertySource doesnt 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"
From the official docs https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#boot-features-external-config-yaml-shortcomings
You might find solutions/workarounds in Spring @PropertySource using YAML
Answered By - Joker