Open in app Sign up Sign in
Read data from YAML file Spring boot
application
Jhamukul · Follow
3 min read · Feb 19, 2022
Listen Share
Topics to be covered:
1. Why YAML is more popular than .properties
2. Learn how to read YAML file in the spring boot application
3. YAML best practices for spring boot application
Let’s take a simple MySQL spring boot connection as an example.
To connect MySQL with the spring boot application, we need to add these configs
to the application.properties file.
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=user
spring.datasource.password=user
If you see the above configuration in this “spring.datasource” common for all.
This is a sample example, Thinks about a large project.
Below config is an example of YAML. Look, It is more formatted and structured
with no duplicates(“spring.datasource”)
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: user
password: user
if you don’t know about YAML and want to learn
https://yaml.org/spec/1.2.2/#chapter-1-introduction-to-yaml
How to read YAML file in spring boot application
Take an example: This is more structured YAML as application.yml.
All application constants/properties wrapped inside myservice-config:
You can do with your spring boot application as well. Trust me it is more readable
and easy to use.
myservice-config:
#My application constants/config properties starts from here
external-service-config:
payment_url: "http://localhost:8081/payment
auth_url: "http://localhost:8083/auth
login_url: "http://localhost:9999/login"
swagger-config:
title: "Dummy Service APIs"
description: "Rest API's for dummy Service"
version: "version-1"
redis-config:
host: localhost
port: 6379
rollbar-config:
access_token: "3egfhcd2c0978888hhh9b0bcdc445"
environment: "local"
aws-config:
access_key: MKIKAINKTWT123345898
secret_key: LMdhahdj777/jjijkajdk7
bucket_region: ap-south-1
cloud_folder: uploads/local
#ends here
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: user
password: user
#Swagger-ui disable and enable by making enabled true or false
springdoc:
api-docs:
enabled: true
How to read these config property, like aws access key, rollbar access key etc
Step 1: Create a class eg like AppProperties
package com.boot.demo.configs.properties;
import lombok.Getter;
import lombok.Setter;
import
org.springframework.boot.context.properties.ConfigurationPropertie
s;
@ConfigurationProperties(prefix = "myservice")
@Getter
@Setter
public class AppProperties {
private final ExternalServiceConfig centralServiceConfig = new
ExternalServiceConfig();
private final SwaggerConfig swaggerConfig = new
SwaggerConfig();
private final RedisConfig redisConfig = new RedisConfig();
private final RollbarConfig rollbarConfig = new
RollbarConfig();
private final AwsConfig awsConfig = new AwsConfig();
@Getter
@Setter
public static class ExternalServiceConfig {
private String paymentUrl;
private String authUrl;
private String loginUrl;
}
@Getter
@Setter
public static class SwaggerConfig {
private String title;
private String description;
private String version;
}
@Getter
@Setter
public static class RedisConfig {
private String host;
private Integer port;
}
@Getter
@Setter
public static class RollbarConfig {
private String accessToken;
private String environment;
}
@Getter
@Setter
public static class AwsConfig {
private String accessKey;
private String secretKey;
private String bucketRegion;
private String cloudFolder;
}
}
Step 2: Add @EnableConfigurationProperties(“your class Name”) in main spring
boot class
@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class)
public class YAMLTestDemoApplication {
public static void main(String[] args) {
SpringApplication.run(YAMLTestDemoApplication.class, args);
}
}
Step 3: If your application doesn’t have annotationProcessor then add
annotationProcessor dependency in pom.xml or build.gradle.
Dependency of annotationProcessor for gradle spring boot application.
annotationProcessor "org.springframework.boot:spring-boot-
configuration-processor"
Now AppProperties contains all myservice-config details and it’s ready to use.
How do we use
Sample example how you can use AppProperties/YAML data in configuration.
@Configuration
@AllArgsConstructor
public class AwsS3Client {
private final AppProperties appProperties;
@Bean
public AmazonS3 getClient() {
final BasicAWSCredentials basicCredentials = new
BasicAWSCredentials(appProperties.getAwsConfig().getAccessKey()
, appProperties.getAwsConfig().getSecretKey());
return AmazonS3ClientBuilder.standard()
.withCredentials(new
AWSStaticCredentialsProvider(basicCredentials))
.withRegion(appProperties.getAwsConfig().getBucketRegion())
.build();
}
}
Note: How you can enable or disable swagger-ui in different profiles.
UseCase: I don’t need swagger-ui in production env so no one can use it.
Add this configuration to your production’s .yml file
springdoc:
api-docs:
enabled: false
Spring Boot Yml Yaml S3 Bucket Swagger Ui
Follow
Written by Jhamukul
77 Followers
More from Jhamukul
Jhamukul
Spring boot: Setting a unique id per request
Spring boot: Setting a unique id per request
Sometimes it is very hard to track all logs or the next or previous ones that are related to a
specific log in distributed microservice.
3 min read · Sep 6, 2022
144 4
Jhamukul
How to caught Async Exception Spring boot application
How do we track and caught async exception that occurs during the async method flow
across the application?
2 min read · Feb 19, 2022
44
Jhamukul
Spring boot: Scaling with Redis Pub/Sub
There are many famous messaging queues. like Kafka, RabbitMQ etc
3 min read · Dec 16, 2022
4 1
Jhamukul
Spring boot: Scale file storage with AWS S3
How do we store files?
6 min read · Feb 11
17
See all from Jhamukul
Recommended from Medium
Shashi Kumar
Using a CrudRepository to read records in Spring Batch:
RepositoryItemReader
Using JPA’s Repository for reading items using ItemReader in Spring Batch.
5 min read · Aug 9
1
Alexander Obregon
Using Spring’s @Retryable Annotation for Automatic Retries
Introduction
11 min read · Sep 17
41 1
Lists
General Coding Knowledge
20 stories · 707 saves
Dennis in Level Up Coding
How to deal with nested entities in Spring Controller
Creating a webservice with Spring is almost trivial, you usually won’t go wrong by following
the tutorials. However, things can get tricky…
4 min read · Jun 28
52
Mert Kağan Aktaş
Spring Data REST: Say Goodbye to Controller and Service.
In the rapidly evolving landscape of software development, managing database access and
operations has seen significant advancements. One…
6 min read · Oct 31
1.4K 34
Zeeshan Adil in JavaToDev
Spring Boot 3 + Spring Security 6 : JWT Authentication & Authorization
you’ll learn how to implement JWT authentication and authorization in a Spring Boot 3.0
application using Spring Security 6 You’ll see how…
12 min read · Oct 29
183 4
Hasan Khan in Stackademic
Connecting multiple databases in Spring boot
In this tutorial we are going to learn how to connect multiple database in spring boot
application.
3 min read · Oct 2
12
See more recommendations