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]
|
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Pooja Agarwal
Pooja is an MCA and oracle certified associate. She has good knowledge of core Java , advanced Java and Hibernate.