Using Application yaml In Spring Boot

Posted By : Pooja Agarwal | 26-Dec-2017

There are many ways to configuring spring application. we can use properties file or yaml for specifying the application configuration.In any application we created separate files for each environment like development staging and production , if we are using prperties file. But we can use all profiles in a single yml file in spring boot.YAML files can not loaded via @PropertySource annotation in spring boot.If we are using @PropertySource then we need properties file.

Spring boot uses SnakeYAML library for yaml support. If Snakeyml library is not included in classpath then spring application class will automatically supports YAML .If we use starter POM then spring boot starter loads yml file automatically.If YAML file is incomplete then Snakeyml parser is unable to detect ,but XML parser always check for well formed document. 

Now we saw that how can we configure the spring application through YAML configuration files. 

application.yml

spring:

    profiles: 

        active:"test"

---

spring:

   profiles: test

name: dev

environment: test

urls:

    -www.abc.test.com

    -www.xyz.test.com 

---

spring: 

    profiles: prod 

name:prod 

environment: production

urls: 

    -www.abc.com

    -www.xyz.com

The three dashes separating the two profiles indicate the start of new document so all the profiles can be described in same YAML file.

Confg class for YAML file(applicationConfig.java)

 

@Configuration 
@ConfigurationProperties 
public class applicationConfig { 

 private String name; 

  private String environment; 

 private List<String> urls = new ArrayList<>(); 

//standard getter setter }

Application.java

 

@SpringBootApplication

 public class Application implements CommandLineRunner{

     @Autowired

       private applicationConfig myconfig;    
       public static void main(String[] args){

         SpringApplication app = new SpringApplication(Application.class)

         app.run();

     }

    public void run(String... args) throws Exception {

       System.out.println("using environment : "+mycofig.getEnvironment());

       System.out.println("name :"+myconfig.getName());

       System.out.println("urls :"+myconfig.getUrls());

   }
}

The output on command line is:

using environment : dev

name: test

urls : [www.abc.test.com , www.xyz.test.com]

 
 

About Author

Author Image
Pooja Agarwal

Pooja is an MCA and oracle certified associate. She has good knowledge of core Java , advanced Java and Hibernate.

Request for Proposal

Name is required

Comment is required

Sending message..