Close

Spring Boot - Using YAML property files

[Last Updated: Jul 24, 2017]

Spring boot supports YAML format for storing external properties. We can create application.yml as an alternative to application.properties. Or we can even use both of them in the same application.

Example

src/main/resources/application.yml

app:
 title: Boot ${app} @project.artifactId@
spring:
    main:
     LogStartupInfo: false

In above file, we are specifying app.title and spring.main.logStartupInfo properties. We are also using ${} and @...@ placeholders. (check out the last tutorial)

Let's create application.property as well:

src/main/resources/application.properties

spring.main.banner-mode=off 

The Main class

@SpringBootConfiguration
public class ExampleMain {
    @Bean
    MyBean myBean() {
        return new MyBean();
    }

    public static void main(String[] args) throws InterruptedException {
        SpringApplication bootApp = new SpringApplication(ExampleMain.class);
        ConfigurableApplicationContext context = bootApp.run(args);
        MyBean myBean = context.getBean(MyBean.class);
        myBean.doSomething();
    }

    private static class MyBean {

        @Value("${app.title}")
        private String appTitle;

        public void doSomething() {
            System.out.printf("App title : %s%n", appTitle);
        }
    }
}

Output

mvn -q spring-boot:run -Dapp=Example
2017-07-24 21:24:05.842  INFO 15608 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@436a4e4b: startup date [Mon Jul 24 21:24:05 CDT 2017]; root of context hierarchy
App title : Boot Example yaml-properties
2017-07-24 21:24:06.052 INFO 15608 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@436a4e4b: startup date [Mon Jul 24 21:24:05 CDT 2017]; root of context hierarchy

Example Project

Dependencies and Technologies Used:

  • Spring Boot 1.5.4.RELEASE
    Corresponding Spring Version 4.3.9.RELEASE
  • spring-boot-starter : Core starter, including auto-configuration support, logging and YAML.
  • JDK 1.8
  • Maven 3.3.9

Using application.yml Select All Download
  • yaml-properties
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
          • application.yml

    See Also