

How to write logs to a file in Spring Boot
Tell spring boot to write logs to disk, instead of just the console.
Updated: 11 April 2022
“Hey, why isn’t my Spring Boot application writing logs to a file?”
You probably noticed when you first started learning Spring Boot. You looked for a log file, but it wasn’t there.
All of the logs are just spewed out to the console, and nothing gets written to disk. How useful is that?
So you re-ran your app, and then copied the logs somehow, and pasted them into Notepad so you could explore them.
How do you get Spring Boot to write logs to a file?
As with most things in Spring Boot:
You should probably use Spring’s default behaviour, unless you really, really need something different
Try to write as little code as possible – this usually means setting some configuration properties or adding annotations
In this article I’m going to cover the quickest way to do write logs to a file, with minimum configuration. This means using Spring’s preferred logging framework, Logback.
How Spring Boot’s logging works
As with most features in Spring Boot, logging is configured in an opinionated manner.
This means that there is a “standard” Spring Boot way to do things, which is automatically implemented for you, unless you choose otherwise.
(Sometimes this can look a bit like sorcery.)
Logging gets added by spring-boot-starter-web
Logging is configured automatically when you add the spring-boot-starter-web dependency to your project.
A new, freshly-generated Spring Boot application (e.g. with the Spring Initializr) doesn’t come with any explicit logging configuration, and uses Logback by default.
( Logback is a logging framework for Java, and a successor to the old log4j .)
How to customise Spring Boot’s logging configuration
You can customise the default logging configuration in one of these ways:
Setting some Spring Boot logging properties – which can go in your application.properties , application.yml , or as environment variables in your shell
Adding a logback.xml onto the classpath, which Spring Boot will detect, and use to configure Logback
Adding a logback-spring.xml onto the classpath, which Spring Boot will detect, and use to configure Logback
How to write logs to a file with Spring Boot
To make Spring Boot write to a log file, you can set the logging.file.path property, either:
in your application.properties file
or in another way, like in an environment variable
Let’s see how these look.
Configuring the file name and path
To make Spring Boot write its log to disk, set the path and filename.
You can set the path with logging.file.path in your application.properties file, e.g.:
With this configuration, Spring Boot will write to the console and also to a log file called spring.log , at the path you specify.
If you want to choose your own log filename instead of spring.log , then you can set the property logging.file.name , in your application.properties , e.g.:
How do you rotate the log file?
If you want to rotate the log file (start a new log file when the current one gets too big), look at setting these properties in your app:
logging.file.max-size
logging.file.max-history
Configuring logging using environment variables
Just like most Spring Boot properties, you can set these properties using environment variables instead, if you like.
Just convert each property to upper-case, and change dots to underscores. So you can use environment variables like this:
How does this work?
How does this trick work? How can we find out information like this ourselves?
It’s nice to understand the “why” sometimes.
So let’s take a look:
In the source code of LogFile , a class in Spring Boot, there’s a comment which explains the main behaviour:
“Log output files are specified using logging.file , logging.path , or Environment properties. If the logging.file property is not specified "spring.log" will be written in the logging.path directory.
The comment tells us exactly how Spring will configure logging, and the properties that we need to set.
How the magic works
How does Spring detect Logback and abstract it away from us?
Looking around the source code, I found these relevant clues (hunted down in Spring Boot v2.6.6):
Logback should appear on the classpath in most Spring Boot projects because… spring-boot-starter-web includes the dependency spring-boot-starter-logging , which includes logback as a dependency.
Spring’s logging system detects Logback because… The abstract class LoggingSystem contains some code which detects and returns the logging system that’s currently in use. It checks which classes are present in the classloader.
Spring knows how to write logs with Logback because… There’s a subclass of LoggingSystem , called LogbackLoggingSystem , which basically configures and works with Logback.
We don’t need to configure Logback ourselves because… Inside DefaultLogbackConfiguration , Spring Boot does some programmatic auto-configuration of Logback for us, so we don’t need to configure it manually.
Magic? Perhaps. :-)
Shouldn’t Spring Boot just write logs to a file by default?
Good question.
The answer to that question might be explained by the fact that Spring Boot is designed to run in environments at large scale.
At scale, managing and maintaining log files starts to become a headache.
Once you start running even just a few of Spring Boot apps in your data centre, it’s going to become painful to rotate and search through hundreds of log files.
Having said that:
Not everyone is running super-scale Netflix-level microservices. And neither is everyone using bleeding-edge container platforms like Kubernetes .
Sometimes, you just want a good old log file which you can write to, and use to check your app is running.
And that’s okay!
Spring Boot Application Configuration with YAML

This guide will introduce you to YAML and the YAML support with the various application configuration options that are present in Spring Boot.

You will learn
- What is application configuration?
What is YAML?
- What are the advantages of YAML?
- How do you specify application configuration using YAML with Spring Boot?
YAML is a human readable serialization language
YAML stands for Yet Another Markup Language
Let’s consider an example
application.properties
Above property file is cool but it is not very readable.
Let’s consider the same example in YAML format: application.yaml
- is more readable
Spring Boot and YAML
Spring Boot has excellent support for YAML configuration.
application.yaml
Example 3 - Dynamic Configuration
Complete project with code example - https://github.com/in28minutes/spring-boot-examples/tree/master/spring-boot-tutorial-basics-configuration
Just Released

Related Articles

Spring Profile - Quick Tutorial for Beginners

Microservices Architectures - What is Service Discovery?

Index - 500+ Videos

Spring Boot Tutorials for Beginners
Introduction to spring boot framework - a quick tutorial for beginners.

Introduction To Spring Data Rest - Quick Tutorial for Beginners

Spring Data and Spring Data JPA - Quick Tutorial for Beginners
Spring batch tutorial for beginners.

What Are Spring Projects?
Getting started with spring boot - 7 things a beginner should know.

Versioning RESTful Services - Spring Boot REST API
Creating a soap web service with spring boot starter web services, 20+ spring boot projects with code examples, spring boot rest api projects with code examples, spring boot exception handling for restful services errors, related courses.

Monolith to Microservices: Crafting the Winning Kafka Strategy | Join Webinar
Login Contact Us
How to Work with Apache Kafka in Your Spring Boot Application
Get started with confluent, for free, watch demo: kafka streaming in 10 minutes.
- Igor Kosandyak
Choosing the right messaging system during your architectural planning is always a challenge, yet one of the most important considerations to nail. As a developer, I write applications daily that need to serve lots of users and process huge amounts of data in real time.
Usually, I use Java with the Spring Framework (Spring Boot, Spring Data, Spring Cloud, Spring Caching, etc.) for this. Spring Boot is a framework that allows me to go through my development process much faster and easier than before. It has come to play a crucial role in my organization. As the number of our users quickly grew, we realized our apparent need for something that could process as many as 1,000,000 events per second.
When we found Apache Kafka ® , we saw that it met our needs and could handle millions of messages quickly. That’s why we decided to try it. And since that moment, Kafka has been a vital tool in my pocket. Why did I choose it, you ask?
Apache Kafka is:
- Fault tolerant
- A great publish-subscribe messaging system
- Capable of higher throughput compared with most messaging systems
- Highly durable
- Highly reliable
- High performant
That’s why I decided to use it in my projects. Based on my experience, I provide here a step-by-step guide on how to include Apache Kafka in your Spring Boot application so that you can start leveraging its benefits too.
Prerequisites
- Use Confluent Cloud , fully managed Apache Kafka as a service, with the promo code SPRING200 to receive $200 of free usage * or download Confluent Platform
- Follow the step-by-step instructions, and you’ll get Kafka up and running in your local environment
I recommend using the Confluent CLI for your development to have Apache Kafka and other components of a streaming platform up and running.
What you’ll get out of this guide
After reading this guide, you will have a Spring Boot application with a Kafka producer to publish messages to your Kafka topic, as well as with a Kafka consumer to read those messages.
And with that, let’s get started!
Table of contents
Step 1: Generate our project Step 2: Publish/read messages from the Kafka topic Step 3: Configure Kafka through application.yml configuration file Step 4: Create a producer Step 5: Create a consumer Step 6: Create a REST controller
Step 1: Generate our project
First, let’s go to Spring Initializr to generate our project. Our project will have Spring MVC/web support and Apache Kafka support.

Once you have unzipped the project, you’ll have a very simple structure. I’ll show you how the project will look like at the end of this article so you can easily follow the same structure. I’m going to use Intellij IDEA, but you can use any Java IDE.
Step 2: Publish/read messages from the Kafka topic
Now, you can see what it looks like. Let’s move on to publishing/reading messages from the Kafka topic.
Start by creating a simple Java class, which we will use for our example: package com.demo.models;

Step 3: Configure Kafka through application.yml configuration file
Next, we need to create the configuration file. We need to somehow configure our Kafka producer and consumer to be able to publish and read messages to and from the topic. Instead of creating a Java class, marking it with @Configuration annotation, we can use either application.properties file or application.yml . Spring Boot allows us to avoid all the boilerplate code we used to write in the past, and provide us with much more intelligent way of configuring our application, like this:
If you want to get more about Spring Boot auto-configuration, you can read this short and useful article . For a full list of available configuration properties, you can refer to the official documentation .
Step 4: Create a producer
Creating a producer will write our messages to the topic.
We just auto-wired KafkaTemplate and will use this instance to publish messages to the topic—that’s it for producer!
Step 5: Create a consumer
Consumer is the service that will be responsible for reading messages processing them according to the needs of your own business logic. To set it up, enter the following:
Here, we told our method void consume (String message) to subscribe to the user’s topic and just emit every message to the application log. In your real application, you can handle messages the way your business requires you to.
Step 6: Create a REST controller
If we already have a consumer, then we already have all we need to be able to consume Kafka messages.
To fully show how everything that we created works, we need to create a controller with single endpoint. The message will be published to this endpoint, and then handled by our producer.
Then, our consumer will catch and handle it the way we set it up by logging to the console.
Let’s send our message to Kafka using cURL:

Basically, that’s it! In fewer than 10 steps, you learned how easy it is to add Apache Kafka to your Spring Boot project. If you followed this guide, you now know how to integrate Kafka into your Spring Boot project, and you are ready to go with this super tool!
You can find all the code in this article on GitHub .
To learn more about using Spring Boot with Apache Kafka, check out this free course with expert videos and guides.
You can also sign up for Confluent Cloud , a fully managed event streaming platform powered by Apache Kafka, and use the promo code SPRING200 for an additional $200 of free Confluent Cloud usage. *
Further reading
- Code samples for Spring Boot and Apache Kafka
- Spring for Apache Kafka Deep Dive – Part 1: Error Handling, Message Conversion and Transaction Support
- Spring for Apache Kafka Deep Dive – Part 2: Apache Kafka and Spring Cloud Stream
- Spring for Apache Kafka Deep Dive – Part 3: Apache Kafka and Spring Cloud Data Flow
- Spring for Apache Kafka Deep Dive – Part 4: Continuous Delivery of Event Streaming Pipelines
This is a guest post by Igor Kosandyak, a Java software engineer at Oril, with extensive experience in various development areas.
Did you like this blog post? Share it now
Subscribe to the confluent blog.

Introducing Apache Kafka 3.6
Apache Kafka 3.6 is here! This release includes Tiered Storage (Early Access), the ability to migrate clusters from ZooKeeper to KRaft with no downtime, the addition of a grace period to stream-table joins, & more!
- Satish Duggana

An Introduction to Apache Kafka Consumer Group Strategy
Ever dealt with a misbehaving consumer group? Imbalanced broker load? This could be due to your consumer group and partitioning strategy!
- Lucia Cerchie

JavaTechOnline
Making java easy to learn, how to write spring boot application properties files.
- Spring Boot
Last Updated on November 1st, 2023

Furthermore, Spring Boot already provides some of the ready-made keys that we use most of the times in our project. Sometimes, we need to create custom properties files in order to fulfil the business requirements. So, we will discuss all about them in this article step by step. Additionally, if you are going to appear in any Spring Boot interview, you are expected to get at least one question from this article. Let’s go through our article ‘How to Write Spring Boot Application Properties Files’ and its related concepts step by step.
Table of Contents
What is application.properties in Spring Boot?
In a Spring Boot Application, ‘application.properties’ is an input file to set the application up. Unlike the standard Spring framework configuration, this file is auto detected in a Spring Boot Application. It is placed inside “src/main/resources” directory. Therefore, we don’t need to specifically register a PropertySource, or even provide a path to a property file.
An application.properties file stores various properties in key=value format. These properties are used to provide input to Spring container object, which behaves like one time input or static data.
What types of keys does an application.properties contain?
An application.properties file contains two types of keys : pre-defined keys, and programmer defined keys.
Pre-defined Keys
Spring framework provides several common default properties to specify inside application.properties such as to support database, email, JPA, Hibernate, Logging, AOP etc. We can find the list of Common Application Properties from Spring Official Documentation .
However, we don’t need to define all the default properties every time. We can define what are required for our application at present. This is also a benefit of using Spring Boot where it reduces XML based configurations and customize them to simple properties.
Programmer-defined Keys
A programmer can also define project specific keys whenever required. We will discuss about how to define them in the following sections of this article.
What are the valid locations of Properties files in the Project? How to load them?
Generally, there are two valid locations for Properties file:
1) src/main/resource (classpath:) Syntax for this is: @PropertySource(“classpath:application.properties”)
2) Inside project folder ( file:/) Syntax for this is:@PropertySource(“file:/application.properties”)
How to read keys of the properties file into the application?
In order to read values from keys, we have two approaches:
Using @Value Annotation
This annotation is provided by the Spring Framework. To read one key from the properties file, we need to declare one variable in our class. Moreover, we need to apply the @Value annotation at the variable with the key as a parameter to it. It’s like @Value(“${key}”)
♥ At a time we can read one key value into one variable. For example, if we have 10 keys, then we should write @Value on top of 10 variables.
♥ If the key is not present in the properties file and we try to read using @Value() then it will throw an Exception: IllegalArgumentException: Could not resolve placeholder ‘my.app.id’ in value “${my.app.id}”
Using @ConfigurationProperties Annotation
This is provided by Spring Boot. We will discuss about in detail in the subsequent sections.
How does the @Value work internally in Spring?
First ‘application.properties’ file is loaded using code like @PropertySource(“classpath:application.properties”). Now, Spring container creates one MEMORY “Environment” (key-val pairs) that holds all the key-vals given by Properties file. We can read those values into variable using Syntax @Value(“${key}”). Then, @Value will search for key in Environment memory. If found then value is updated into container object.
How to write Custom Properties file in Spring Boot?
There are some certain steps to write our own properties file. Let’s follow below steps:
Step#1: Define your properties file with any name with extension .properties
Right click on ‘src/main/resources’ > new > file > Enter name : product.properties Additionally, Enter content as applicable. For example,
Step#2: At Main class/Starter class, apply @PropertySource annotation In our case, the Syntax will be: @PropertySource(“classpath:product.properties”)
For Example, let’s assume we are going to define a ‘product.properties’
Step #1: Create a Spring Boot Project
Here, we will use STS(Spring Tool Suite) to create our Spring Boot Project. If you are new to Spring Boot, visit Internal Link to create a sample project in spring boot.
Step #2: Create a new properties file under src/main/resources folder
Let’s name it product.properties.
Step #3: Create a class to read values from properties file
In order to read values from properties file, let’s create a class Product.java as below. Don’t forget to apply @Component annotation.
Step#4: Apply @PropertySource(“—“) at the main/starter class
In main or starter class whichever is applicable in your case, apply @PropertySource(“classpath:product.properties”) in order to tell Spring Container that you are using a custom properties file as below. Moreover, we need to print the product class to check the values.
Step#4: Test the output
Right click on the project, Run As > Spring Boot App. Now check the output at console. You will see the below output.
Product [title=my product, version=2.5]
How can we create and load multiple properties files in the application?
It is absolutely possible to create & load multiple properties files in the application with the help of @PropertySource itself. Below is the syntax to use it in case of multiple properties.
If we define the same key with different values in different properties files, which one will be selected?
In this case, the last loaded properties file key will be considered.
For example, consider the below properties file declaration.
From the above example, first it will check in ‘abc.properties’ for the given key, if the key also exists in ‘xyz.properties’, the values will be reflected from ‘xyz.properties’, as it is loaded at the last. ♦ if it doesn’t exist in both the files, priority is for ‘application.properties’.
How to map multiple properties with a single variable? When to use @ConfigurationProperties annotation?
As aforementioned, we can use @Value annotation to read only one property from the properties file at a time into our code. Spring core framework provides this feature. Suppose we have a requirement where we need to read multiple properties from properties file in our code. Here, we will make use of @ConfigurationProperties annotation. Furthermore, @ConfigurationProperties also supports working with Collections and Bean Type (class Type). Actually, we will have this kind of scenario multiple times in our project. Let’s be aware that Spring Boot provides the @ConfigurationProperties annotation.
What are the general guidelines/rules to use @ConfigurationProperties annotation?
1) The prefix provided inside the @ConfigurationProperties annotation must match with the prefix given in the properties file, else variable will not get the correct values.
2) We must generate getters and setters for the variables that we used to map with the keys of properties file.
♥ Note: Since @Value uses refection based data read, hence getters & setters are not required in that case .
♥ Note: While applying @ConfigurationProperties annotation, you may get a warning “When using @ConfigurationProperties it is recommended to use ‘spring-boot-configuration-processor’ to your classpath to generate configuration metadata’. You can resolve it by clicking on the warning and selecting ‘Add to spring-boot-configuration-processor pom.xml’ as shown below in the screenshot. Alternative way to resolve it is that you can manually add the dependency of ‘spring-boot-configuration-processor’ in your pom.xml file.

Example: How to read multiple values from the properties file in our code?
Let’s develop an example of reading multiple values from the properties file in our code. However, in this example we will consider the simplest case. Further, in the subsequent sections, we will cover the complex scenarios.
Step#1: Update the application.properties file
For example, let’s consider below values. Here, each entry is in the form of ‘prefix.variable=value’. Obviously, ‘prefix.variable’ forms the key. Therefore, the last word of the key becomes the variable in our class. On the other hand, the remaining left side part becomes the prefix, which in turn becomes the parameter of @ConfigurationProperties annotation.
Step#2: Create a Runner class and define variables
Let’s create a class and define variables. Here we are taking a Runner class just to test the example easily. Also, let’s follow below guidelines.
1) Apply annotation @ConfigurationProperties(“product.app”) on top of the class. Make sure that prefix as a parameter of this annotation must match with the prefix given in the keys of the properties file. In our case, ‘product.app’ is the prefix.
2) After prefix we have id, code & version respectively in the keys. Hence, these parts of the keys will become the variable names in our class as below.
However, in this example, we have applied @PropertySource(“classpath:product.properties”) in Runner class. We can also apply it at the main class optionally.
Step#3: Check the Output
Now, run the application and check the output. It will be like below.
How to read multiple values from the properties file in our code as a Collection?
We need to follow some guidelines in order to read values from properties file in the form of a Collection in our code. Every developer knows how to define a collection variable in the class. But how can we define the respective values in the properties file is the point of discussion here. Let’s discuss it step by step as below.
List/Set/Array
In case of List, Set and Array, we should use index that starts with zero as below.
prefix.variable[index]=value For example: product.app.info[0]=InfoValue1, product.app.info[1]=InfoValue2, …..and so on.
Map/Properties
Let’s understand a basic difference between Map & Properties first. Map (Interface) Generics Types are provided by Programmer and having multiple Implementations. Properties is a class that stores data with single format key=val (by default converted as String). Here, Map & Properties takes the same format key=value as shown below.
prefix.variable.key=value For example: product.app.category.C1=CategoryValue1, product.app.category.C2=CategoryValue2, …..and so on.
Let’s update the product.properties file as per the guidelines given above.
As we have already discussed why we are using a Runner class here, let’s jump to the example directly as below.
How to read multiple values from the properties file in our code as an Object?
Instead of being a Collection type, suppose our variable is an instance of a particular type. In this case also, we need to follow some guidelines in order to read values from properties file. Let’s discuss it step by step as below.
We can even read properties data into one class object by using HAS-A relation and syntax is as below:
Step#2: Create a model class and define its properties
In order to make a variable of a particular type(Class type), let’s create a model class & define some properties. To illustrate, let’s assume that we have a Brand of the Product. Therefore, we will create a Brand class as step by step as below.
1) Create one class with variables(properties) 2) Generate getters, setters, toString. 3) Use this class as Data Type and create HAS-A variable(reference variable) in other class.
Note: Do not apply @Component over this class type. This object is created only on condition: ‘If data exists in properties file’. This work is taken care by the annotation @ConfigurationProperties.
Step#3: Create a Runner class and define variables
Step#4: check the output, what is yaml(.yml) file .
YAML is a latest format to define key:val pairs without having duplicate words in more than one key. In other words, YAML is a convenient format for specifying hierarchical configuration data. It uses “Snake YAML” API and it is added by default in every Spring Boot Application. Moreover, it has following benefits for the developer.
1) It has a good look and feel and even easy to read. 2) No duplicate words in levels/keys. 3) Auto-Parsing supported using Snake-YAML API. 4) Also, easy to write.
What are the rules/guidelines to write a YAML(.yml) file?
1) Unlike .properties file, dot(.) and equals(=) are not allowed, but only colon(:) is allowed. 2) Before each value in .yml file, we must provide exactly one blank space. 3) After every colon(:) symbols, go to new line/change line and provide spaces, if key is still incomplete. 4) Spaces count/indentation/alignment must be matching for the same level of key. 5) Do not provide any duplicate levels/hierarchy.
How to convert into YAML(.yml) file from a .properties file?
Generally, there are two ways to convert a .properties file into a .yml file: 1) Manually 2) With the help of IDE like STS.
1) Replace all occurrences of dot(.) and equals(=) with colon(:) 2) Follow rules/guidelines given in the above section.
If your file has lengthy content, it will take too much effort to convert.
If you are using an IDE like STS(Spring Tool Suite), you can perform conversion in a single click as below.
Right click on .properties file and select option: Convert .properties to .yaml’ and finally click on ‘OK’. You will get a .yml file in less than a minute.
Example: Converting ‘.properties’ into ‘.yml’
For example, Let’s convert our ‘product.properties’ into ‘product.yml’.
product.properties
Apply any one of the method of conversion given in above section. Your final ‘product.yml’ file will look like below.
product.yml
Can we modify/rename file name application.properties in spring boot.
Yes we can, but it is not loaded by Spring Boot by default. By default, Spring Boot checks ‘application.properties’ under location ‘src/main/resources’. If we want to load other files, follow below steps:
1) Create your custom file at the same location (‘src/main/resources’) 2) Apply @PropertySource annotation at starter/runner class and provide the name of your custom file as a parameter to it. For example: @PropertySource(“classpath:xyz.properties”) here, the classpath is ‘src/main/resource’ folder
Alternatively, we can also keep this file inside project folder (file:/ = project folder)
If a key is present in both application.properties and our custom properties file, then which one will be selected?
Key from ‘application.properties’ will always have a higher priority.
Leave a Reply Cancel reply
Insert/edit link.
Enter the destination URL
Or link to existing content
- Java Arrays
- Java Strings
- Java Collection
- Java 8 Tutorial
- Java Multithreading
- Java Exception Handling
- Java Programs
- Java Project
- Java Collections Interview
- Java Interview Questions
- Spring Boot

- Explore Our Geeks Community
- Spring Boot - MongoRepository with Example
- Spring Boot - Integrating Hibernate and JPA
- Spring Boot JpaRepository with Example
- Spring Boot - CRUD Operations using MongoDB
- Spring Boot - Spring Data JPA
- Upload Multiple Files in Spring Boot using JPA, Thymeleaf, Multipart
- Spring Boot - Difference Between CrudRepository and JpaRepository
- Spring Boot - CrudRepository with Example
- Spring Boot - application.yml/application.yaml File
- Spring Boot - CRUD Operations using MySQL Database
- How to Implement One to Many Mapping in Spring Boot?
- How to Run Your First Spring Boot Application in Eclipse IDE?
- How to Run Spring Boot Application?
- Spring Boot - Application Properties
- Spring Boot - H2 Database
- Spring Boot - CRUD Operations
- Spring Boot - REST Example
- Spring Boot - Change Port
- Spring Boot - Hello World Example
- What is Command Line Runner Interface in Spring Boot?
- How to Make a Simple RestController in Spring Boot?
- How to Implement Simple Authentication in Spring Boot?
- What is PathVariable in the Spring Boot?
- How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA?
- How to Get the Body of Request in Spring Boot?
Spring Boot – Application Properties
As we already know Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because it’s a rapid production-ready environment that enables the developers to directly focus on the logic instead of struggling with the configuration and set-up. In Spring Boot, whenever you create a new Spring Boot Application in spring starter, or inside an IDE (Eclipse or STS) a file is located inside the src/main/resources folder named as application.properties file which is shown in the below image as shown below as follows:
Geeks, now you must be wondering what does this file do? What are the major roles of this file during development? So in a spring boot application, application.properties file is used to write the application-related property into that file. This file contains the different configuration which is required to run the application in a different environment, and each environment will have a different property defined by it. Inside the application properties file, we define every type of property like changing the port, database connectivity, connection to the eureka server, and many more. Now let’s see some examples for better understanding.
Example 1: To Change the Port Number
Sometimes when you run your spring application you may encounter the following type of error

The error is Port 8989 was already in use. So in this case you may kill that process that is running on this port number or you may change your port number and rerun your application. So where do you have to change your port number? e.g in the application.properties file .

So as given in the above screenshot you can change your port number by the following line
Example 2: To define the name of our application
To define the name of our application you can write the properties like this
So you can see this represents the property as key-value pair here, every key associated with a value also.
Example 3: Connecting with the MySQL Database
To connect with the MySQL Database you have to write a bunch of lines. You can write the properties like this
Example 4: Connecting with the H2 Database
H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It is generally used in unit testing. It stores data in memory, not persist the data on disk. To connect with the H2 Database you have to write a bunch of lines. You can write the properties like this
Example 5: Connecting with the MongoDB Database
To connect with the MongoDB Database you have to write a bunch of lines. You can write the properties like this
Example 6: Connecting with the Eureka Server
Eureka Server is an application that holds information about all client-service applications. Every Microservice will register into the Eureka server and the Eureka server knows all the client applications running on each port and IP address. Eureka Server is also known as Discovery Server. You can write the properties like this
Example 7 : Connecting with the PostgreSQL
PostgreSQL is a free and open-source relational database management system. To connect with the PostgreSQL Database you have to write a bunch of lines. You can write the properties like this.
Note : The value written here is sample data. Please write the values as per your requirements. But the keys remain the same.
application.yml/application.yaml file
The application.properties file is not that readable. So most of the time developers choose application.yml file over application.properties file. YAML is a superset of JSON, and as such is a very convenient format for specifying hierarchical configuration data. YAML is more readable and it is good for the developers to read/write configuration files. For example, let’s pick some of the properties files that we have explained above, and let’s write them in YAML format.
Case 1: Let’s pick above example 3 where we were connecting with the MySQL Database , the corresponding properties will be as follows:
Case 2: Let’s pick above example 6 where we were connecting with the Eureka Server, the corresponding properties will be as follows:
Please Login to comment...

- nandinigujral
- Java-Spring-Boot
Please write us at contrib[email protected] to report any issue with the above content
Improve your Coding Skills with Practice

IMAGES
VIDEO
COMMENTS
1. Overview One of the ways of configuring Spring applications is using YAML configuration files. In this quick tutorial, we'll configure different profiles for a simple Spring Boot application using YAML. Further reading: A Quick Guide to Spring @Value
But sometimes there is another file is located inside the src/main/resources folder named as application.yml/application.yaml file and the code present inside this file is present in a hierarchical format which is shown in the below image: So what's this application.yml file?
1. Overview A common practice in Spring Boot is using an external configuration to define our properties. This allows us to use the same application code in different environments. We can use properties files, YAML files, environment variables and command-line arguments.
Configuring the file name and path. To make Spring Boot write its log to disk, set the path and filename. You can set the path with logging.file.path in your application.properties file, e.g.: # Examples for Spring Boot 2.x logging.file.path=. # write logs to the current directory logging.file.path=/home/logs # write logs to /home/logs logging ...
1 I have a little SpringBoot Application, which can execute different functions via OpenLdap. getUser createUser deleteUser etc. That works fine. Now i want to create an application.Yml, where i can manage different environments with different credentials. I read some tutorials, but i still have some understanding problems.
In the default structure of a Spring Boot web application, you can locate the application.yml file under the /resources folder. Spring boot uses Logback as the default logging provider. 1. Default Logging with Spring Boot To understand default spring boot logging, let's put logs in spring boot hello world example.
6 Answers Sorted by: 59 remove @PropertySource annotation, you not need it rename your scheduling.yml into src/main/resources/application-scheduling.yml add in src/main/resources/application.yml file next line: spring.profiles.include: 'scheduling' Share Follow edited Nov 9, 2016 at 5:47 answered Nov 9, 2016 at 5:40 Maksim Kostromin 3,351 1 33 30 2
4 Answers Sorted by: 84 Well, they are just different data formats. Which one's nicer and easier to read? That's obviously subjective. Here's a useful blog post. As far as spring-boot configuration is concerned, note that there's only one documented shortcoming of using YAML. Per the documentation:
1. Overview In this short tutorial, we're going to have a closer look at how to map a YAML list into a List in Spring Boot. We'll start with some background on how to define lists in YAML. Then we'll dig deeper to see how to bind YAML lists to List s of objects. 2. Quick Recap About Lists in YAML
Example 1 application.properties server.port = 9080 application.yaml server: port: 9080 Example 2 application.properties app.name=in28Minutes app.description=$ {app.name} is your first Spring Boot application welcome.message=Welcome message from property file! Welcome to $ {app.name} application.yaml
In short, create a application.yml in the src/resources folder, Spring Boot will load and parse .yml file automatically and bind the values into the classes which annotated with @ConfigurationProperties P.S YAML files cannot be loaded by using the `@PropertySource` 1. YAML and Properties application.yml
1. Overview In this quick tutorial, we'll learn how to inject a map from a YAML file in Spring Boot. First, we'll start with a little bit of insight on YAML files in Spring Framework. Then we'll demonstrate how to bind YAML properties to a Map with a practical example. 2. YAML Files in Spring Framework
Step 1: Generate our project. First, let's go to Spring Initializr to generate our project. Our project will have Spring MVC/web support and Apache Kafka support. Once you have unzipped the project, you'll have a very simple structure. I'll show you how the project will look like at the end of this article so you can easily follow the ...
How to write Custom Properties file in Spring Boot? Step #1: Create a Spring Boot Project. Step#2: Create a new properties file under src/main/resources folder. Step#3: Create a class to read values from properties file. Step#4: Apply @PropertySource ("—") at the main/starter class. Step#4: Test the output.
One way to include multiple YAML configuration files in an application is by using Spring profiles. This approach takes advantage of Spring's autoloading of YAML configuration files associated with an application profile. Next, let's walk through an example with two .yml files. 2.1. YAML Setup Our first file lists students.
1. Project Structure A standard Maven project structure. 2. @ConfigurationProperties Read the properties or yaml files later. ServerProperties.java
1. Overview In this quick tutorial, we'll show how to read a YAML properties file using the @PropertySource annotation in Spring Boot. 2. @PropertySource and YAML Format Spring Boot has great support for externalized configuration.
Example 2: To define the name of our application. To define the name of our application you can write the properties like this. spring.application.name = userservice. So you can see this represents the property as key-value pair here, every key associated with a value also. Example 3: Connecting with the MySQL Database.
Running spring boot application as below: My port 8080 is in use so I am trying to change it. Also, I deliberately am giving wrong bootstrap server for kafka to see if it takes effect. Also, I deliberately am giving wrong bootstrap server for kafka to see if it takes effect.
If you use Maven, you can run the application by using ./mvnw spring-boot:run. Alternatively, you can build the JAR file with ./mvnw clean package and then run the JAR file, as follows: java -jar target/gs-uploading-files-.1..jar. The steps described here create a runnable JAR. You can also build a classic WAR file.
Prerequisites. Set up the environment. Create a Spring Boot application. Build a Docker container image. Write a Dockerfile. Containerize the app. Push the image to the container registry. Deploy the application on Kubernetes. Create Kubernetes deployment file.