Issue
I am creating a simple spring boot application, that loads a string (ISO-date) from the application.yaml file and tries to put it into a @Value annotated field. If I use a .yaml file the string is obviously converted into a date/calendar and afterwards "toStringed" into a different format. If I use a .properties file the string is passed as-is.
Application
@EnableAutoConfiguration
@Configuration
@ComponentScan
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
SampleComponent c = ctx.getBean(SampleComponent.class);
c.bla();
}
}
Component that should be configured
@Component
public class SampleComponent {
@Value("${dateString}")
private String dateString;
public void bla() {
System.out.println(dateString);
}
}
application.yaml
dateString: 2015-01-09
=> Output: Fri Jan 09 01:00:00 CET 2015
application.properties
dateString=2015-01-09
=> Output: 2015-01-09
For me it is fine to use the properties solution, but I do not understand why this happens?
(Note: When trying to assign the yaml-date to a date field the expected "Cannot convert value of type [java.lang.String] to required type [java.util.Date]: no matching editors or conversion strategy found" Exception is thrown)
Solution
It's happening because Spring Boot uses SnakeYAML for its YAML parsing and SnakeYAML's default behaviour is to create a java.util.Date
from any string that it considers to be a timestamp. If you're interested in learning more, see SnakeYAML's Resolver class for further details including the regex it uses to identify a timestamp.
Answered By - Andy Wilkinson
Answer Checked By - Mildred Charles (JavaFixing Admin)