Google News
logo
Java Spring Boot Interview Questions
Spring Boot is essentially a framework for rapid application development built on top of the Spring Framework. With its auto-configuration and embedded application server support, combined with the extensive documentation and community support it enjoys, Spring Boot is one of the most popular technologies in the Java ecosystem as of date.
 
Here are a few salient features :

* Security
* Logging
* Starters : a set of dependency descriptors to include relevant dependencies at a go
* Auto-configuration : a way to automatically configure an application based on the dependencies present on the classpath
* Actuator : to get production-ready features such as monitoring
The advantages of Spring Boot are listed below :
 
* Easy to understand and develop spring applications.
* Spring Boot is nothing but an existing framework with the addition of an embedded HTTP server and annotation configuration which makes it easier to understand and faster the process of development.
* Increases productivity and reduces development time.
* Minimum configuration.
* We don’t need to write any XML configuration, only a few annotations are required to do the configuration.
Below are the four key components of spring-boot:
 
* Spring Boot auto-configuration.
* Spring Boot CLI.
* Spring Boot starter POMs.
* Spring Boot Actuators.
Spring boot provides numbers of starter dependency, here are the most commonly used :
 
* Data JPA starter.
* Test Starter.
* Security starter.
* Web starter.
* Mail starter.
* Thymeleaf starter.
Well, there are various approaches to create a Spring Boot application using maven, but if I have to name a few, then following are the ways to create a Spring Boot project/ application using maven:
 
* Spring Boot CLI
* Spring Starter Project Wizard
* Spring Initializr
* Spring Maven Project
* One of the ways to create a spring boot project in eclipse is by using Spring Initializer.
 
* You can go to the official website of spring and add details such as version, select maven or Gradle project, add your groupId, artifactId, select your required dependencies and then click on CREATE PROJECT
 
* Once the project is created, you can download it and extract and import it in your eclipse or STS.
 
And see your project is ready!
There is no doubt in the fact that Spring Boot allows the developers to run the same application in different environments. Well, this is done with the support it provides for external configuration. It uses environment variables, properties files, command-line arguments, YAML files, and system properties to mention the required configuration properties. Also, the @value annotation is used to gain access to the properties. So, the most possible sources of external configuration are as follows:
 
Application Properties : By default, Spring Boot searches for the application properties file or its YAML file in the current directory, classpath root or config directory to load the properties.
 
Command-line properties : Spring Boot provides command-line arguments and converts these arguments to properties. Then it adds them to the set of environment properties.
 
Profile-specific properties :  These properties are loaded from the application-{profile}.properties file or its YAML file. This file resides in the same location as that of the non-specific property files and the{profile} placeholder refers to an active profile.
Whenever you will create your spring boot application and run it, Spring boot will automatically detect the embedded tomcat server and deploy your application on tomcat.

After successful execution of your application, you will be able to launch your rest endpoints and get a response.
Difference between Spring and Spring boot are as follows :
 
Spring : 
* Uses XML based configuration.
* Is a dependency injection framework.
* It is basically used to manage the life cycle of java classes (beans). It consists of a lot of boilerplate configuration.
* It takes time to have a spring application up and running and it’s mainly because of boilerplate code.

Spring boot :
* Uses annotations.
* It is a suite of pre- configured frameworks and technologies which helps to remove boilerplate configuration.
* It is used to create a production-ready code.
* An actuator is one of the best parts of spring boot which consists of production-ready features to help you monitor and manage your application. 
 
* With the help of an actuator, you can monitor what is happening inside the running application.

* Actuator dependency figures out the metrics and makes them available as a new endpoint in your application and retrieves all required information from the web. You can identify beans, the health status of your application, CPU usage, and many more with the actuator.
RAD or Rapid Application Development process is an adoption of the waterfall model; it targets developing software in a short period. RAD follow the iterative
 
SDLC RAD model has the following phases :
 
* Business Modeling
* Data Modeling
* Process Modeling
* Application Generation
* Testing and Turnover
This is a frequently asked job interview. Various phases of RAD mode are :
 
Business Modeling : Based on the flow of information and distribution between various business channels, the product is designed.
Data Modeling : The information collected from business modeling is refined into a set of data objects that are significant for the business.
Application Generation : Automated tools are used for the construction of the software, to convert process and data models into prototypes.
Spring boot starter comprises of templates which provide a Rapid Application Development, spring boot starter contains a combination of all the relevant transitive dependencies.  
 
* Spring boot starter is a jar file which predominantly solves the auto-dependency resolution in a spring boot application. 
* Spring boot starter follows the unified pattern, like every dependency start with spring-boot-starter-X, where X will be the name of dependencies.  
* For instance, if we add the dependency like spring-boot-starter-web, the spring boot starter will internally resolve and download all the associated dependencies, add to the application. 
* Spring boot also checks and resolves the transitive dependencies internally.
 
Below are some of the popular Spring boot starters :
 
* Spring-boot-starter-web
* Spring-boot-starter-mvc
* Spring-boot-starter-security
* Spring-boot-starter-jpa
* Spring-boot-starter-tomcat
* Spring-boot-starter-jetty
* Spring-boot-starter-json
Spring boot CLI is a command line interface, which use and run test the microservices application based on spring boot.
 
* Spring Boot CLI is a module of Spring boot application which use to run and test Spring Boot applications from the command prompt.
* When we run Spring Boot applications using CLI, then it internally uses Spring Boot Starter and Spring Boot Autoconfiguration components to resolve all dependencies and execute the application.
* Internally contains Groovy file which is a JAR Dependency Manager to add Spring Boot Defaults and resolve all dependencies automatically. 

Spring Boot CLI operation is a combination of below component :

* Auto Dependency Resolution 
* Auto-Configuration
* Management Endpoints
* Embedded HTTP Servers
 
The benefits that we achieved from using spring boot CLI is, that we don’t need to use any import, no need to do the xml configuration, no web.xml and no dispatcherservlet declaration and no need to create war file manually.
The starters contain a lot of the dependencies you need to get a project up and running quickly and with a consistent, supported set of managed transitive dependencies. All official starters follow a similar naming pattern; spring-boot-starter-*, where * is a particular application. They intend this naming structure to help when you need to find a starter. Third party starters should not start with spring-boot, as they reserve it for official Spring Boot artifacts
 
spring-boot-starter-web : Web and RESTful applications
spring-boot-starter-security : Spring Security
spring-boot-starter-data-jpa : Spring Data JPA
spring-boot-starter-test : Unit testing
spring-boot-starter-hateoas : Add HATEOAS features
spring-boot-starter-data-jpa : Spring Data JPA with Hibernate
It takes a lot of configurations and boilerplate code create a simple Spring MVC application without Spring Boot. Spring Boot Auto Configuration provides an opinionated approach to bootstrap your application. Auto-Configuration will attempt to automatically try to set up our application with default behavior based on the jars in the class-path.For example, if Spring Boot finds HSQLDB in out class-path, it will automatically configure an in-memory database for us. Think of the auto-configuration as an intelligent system which can provide ready to use the application to us based on the configured jars in our class-path.
Spring Boot checks for a META-INF/spring.factories file within your published jar for the auto-configuration classes. To register our custom auto-configuration class, we should use a fully qualified name of the class under the EnableAutoConfiguration in the spring.factories property file.
 
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.javadevjournal.config.HelloServiceAutoConfiguration
This is achievable by Spring Boot Dev Tools module.it’s a powerful tool for development. It helps developers to shorten the development cycle and enable easy deployment and testing during development.
 
To enable this feature, add the following dependency to Maven POM file.
<dependencies>
    <dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>
The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes. Spring Boot enables the developer to use a single annotation instead of using multiple. But, as we know, Spring provided loosely coupled features that we can use for each annotation as per our project needs.
Spring Boot application scans all the beans and package declarations when the application initializes. You need to add the @ComponentScan annotation for your class file to scan your components added to your project.
Spring boot starter is a maven template that contains a collection of all the relevant transitive dependencies that are needed to start a particular functionality.

Like we need to import spring-boot-starter-web dependency for creating a web application.
 
<dependency>
  <groupId> org.springframework.boot</groupId>
  <artifactId> spring-boot-starter-web </artifactId>
</dependency>

 

Yes, we can replace the Embedded Tomcat server with any server by using the Starter dependency in the pom.xml file. Like you can use spring-boot-starter-jetty as a dependency for using a jetty server in your project.
You can use exclude attribute of @EnableAutoConfiguration if you want auto-configuration not to apply to any specific class.
 
//use of exclude
@EnableAutoConfiguration(exclude={className})

@Controller Map of the model object to view or template and make it human readable but @RestController simply returns the object and object data is directly written in HTTP response as JSON or XML.
To enable the spring actuator feature, we need to add the dependency of “spring-boot-starter-actuator” in pom.xml.
 
<dependency>
  <groupId> org.springframework.boot</groupId>
  <artifactId> spring-boot-starter-actuator </artifactId>
</dependency>

 

Debugging logs can be enabled in three ways :
 
* We can start the application with --debug switch.
* We can set the logging.level.root=debug property in application.property file.
* We can set the logging level of the root logger to debug in the supplied logging configuration file.
Spring Boot 2.1.7.RELEASE requires
 
* Java 8 +
* Spring Framework 5.1.9 +
 
Explicit build support
 
* Maven 3.3+
* Gradle 4.4+
 
Servlet Container Support

* Tomcat 9.0 – Servlet Version 4.0
* Jetty 9.4 –  Servlet Version 3.1
* Undertow 2.0 – Servlet Version 4.0
Thymeleaf is a server-side Java template engine used for web applications. It aims to bring natural template for your web application and can integrate well with Spring Framework and HTML5 Java web applications. To use Thymeleaf, you need to add the following code in the pom.xml file :
 
<dependency>    
  <groupId>org.springframework.boot</groupId>    
  <artifactId>spring-boot-starter-thymeleaf</artifactId>    
</dependency>

 

Yes, we can change the port of the embedded tomcat server by using the application properties file. In this file, you have to add a property of “server.port” and assign it to any port you wish to. For example, if you want to assign it to 8081, then you have to mention server.port=8081. Once you mention the port number, the application properties file will be automatically loaded by Spring Boot and the required configurations will be applied on to the application.
Spring Boot Dev Tools are an elaborated set of tools and aims to make the process of developing an application easier. If the application runs in the production, then this module is automatically disabled, repackaging of archives are also excluded by default. So, the Spring Boot Developer Tools applies properties to the respective development environments.  To include the DevTools, you just have to add the following dependency into the pom.xml file :
 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

 

To create a war file in spring boot you need to define your packaging file as war in your pom.xml(if it is maven project).
 
Then just do maven clean and install so that your application will start building. Once the build is successful, just go into your Target folder and you can see .war file generated for your application.
JPA is basically Java Persistence API. It’s a specification that lets you do ORM when you are connecting to a relational database which is Object-Relational Mapping
 
So, when you need to connect from your java application to relational database, you need to be able to use something like JDBC and run SQL queries and then you get the results and convert them into Object instances. 
 
ORM lets you map your entity classes in your SQL tables so that when you connect to the database , you don’t need to do query yourself, it’s the framework that handles it for you.
 
And JPA is a way to use ORM, it’s an API which lets you configure your entity classes and give it to a framework so that the framework does the rest.
User can enable HTTP/2 support by using
 
server.http2.enabled configuration property.

Spring Boot admin is a community project which helps you to manage and monitor your Spring Boot applications.
Yes, it is possible to replace the Embedded Tomcat with any other servers by using the starter dependencies. For that, you can use spring-boot-starter-jetty or as a dependency for according you to your need.
There are three methods to add filter to Spring Boot application :

* Using MVC controller.
* By implementing Filter interface.
* Using FilterRegistrationBean.
LiveReload is a spring-boot-devtools module that includes LiveReload server to trigger a browser refresh when a resource is changed. LiveReload server extensions are available freeware for Firefox, Chrome, and Safari.
It is a way to reload the changes without restarting Tomcat, or Jetty server. Eclipse and Many other IDEs support bytecode hot swapping. If you make any changes that don't affect the method signature, it should reload without side effect.
The advantages of the YAML file than a properties file is that the data is stored in a hierarchical format. So, it becomes very easy for the developers to debug if there is an issue. The SpringApplication class supports the YAML file as an alternative to properties whenever you use the SnakeYAML library on your classpath. The different ways to load a YAML file in Spring Boot is as follows :
 
* Use YamlMapFactoryBean to load YAML as a Map
* Use YamlPropertiesFactoryBean to load YAML as Properties
Spring Data REST is used to expose the RESTful resources around Spring Data repositories. Consider the following example :
 
@RepositoryRestResource(collectionResourceRel = "sample", path = "sample")
public interface SampleRepository
        extends CustomerRepository<sample, Long> {
 
Now, to expose the REST services, you can use the POST method in the following way:
 
{
"customername": "Venkat"
}
 
Response Content

{
"customername": "Venkat"
"_links": {
"self": {
"href": "http://localhost:8080/sample/1"
},
"sample": {
"href": "http://localhost:8080/sample/1"
}
}
 
Observe that the response content contains the href of the newly created resource.
The @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET). Both these methods support the consumes. The consume options are :
 
consumes = “text/plain”
consumes = {“text/plain”, “application/*”}

 

If H2 is not present in the classpath, then you see the following error :
 
Cannot determine embedded database driver class for database type NONE
 
To resolve this error, add H2 to the pom.xml file, and restart your server.

The following code snippet can be added to add the dependency :
 
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

 

First configure mysql in your spring boot application.
Then you can map your entities with your db tables using JPA.
And with the help of save() method in JPA you can directly insert your data into your database
 
@RestController
@RequestMapping("/freetimelearning")
public class Controller {
@Autowired
private final FreeTimeLearningRepository freetimelearningRepository;
public Controller(FreeTimeLearningRepository freetimelearningRepository) {
}
 
In above case, your data which may be in JSON format can be inserted successfully into database.
 
@RequestMapping(method = RequestMethod.POST)
ResponseEntity<?> insert(@RequestBody Course course) {
greatLearningRepository.save(course);
 return ResponseEntity.accepted().build();
}
}

 

The default port number to start your Spring Boot application is 8080.

Just to change the port number, you need to add server.port=8084(your port number) property in your application.properties file and start your application.
This is quite common error in spring boot application which says 404(page not found).
 
We can mostly resolve this in 3 ways :
 
Custom Error Controller : where you will be implementing ErrorController  interface which is provided by SpringFramework and then overriding its getErrorPath() so that you can return a custom path whenever such type of error is occurred.

By Displaying Custom error page : All you have to do is create an error.html page and place it into the src/main/resources/templates path. The BasicErrorController of of springboot will automatically pick this file by default.

By disabling the whitelabel error page : This is the easiest way where all you need to do is server.error.whitelabel.enabled property to false in the application.properties file to disable the whitelabel error page.
* One of the way to bootstrap your spring boot application is using Spring Initializer.

* you can go to the official website of spring  and select your version, and add you groupID, artifactId and all the required dependencies. 
 
* And then you can create your restEndpoints and build and run your project.

* There you go, you have bootstrapped your spring boot application.
To handle exceptions in spring boot, you can use @ControllerAdvice annotation to handle your exceptions globally.
 
In order to handle specific exception and send customized response, you need to use @ExceptionHandler annotation.
CORS stands for Cross-Origin Resource Sharing is a  mechanism implemented by browsers and helps users to authorize cross-domain requests. This mechanism serves as an alternative to less secure and less powerful hacks of the kinds of IFrame or JSONP.
Swagger is a specification and framework implementation for producing a visual representation of RESTful Web Services API. With the help of Swagger, the API consumer can understand and interact with the remote service with a minimal amount of implementation logic. One can compare it to the blueprint of a house.
 
It creates a contract for the RESTful API, detailing all of its resources and operations in a human and machine-readable format. It allows the documentation to be placed at the same project as the server allowing easy development, discovery, and integration of the application.
 
It is typically defined in a YAML file, which makes it easy to comprehend both by developers, API clients, and business users, etc. Swagger can be integrated with Gradle for enabling code generation feature, which is used for generating REST controllers and domain classes (POJO) for the application. This helps in maintaining the API definition and code always in sync.
Hibernate is a JPA (Java Persistence API) implementation providing ORM (Object-relational mapping) for mapping, storing, updating and retrieving application data from relational databases to Java objects and vice versa. Hibernate maps Java classes to database tables and from Java data types to SQL data types, hence programmer is relieved from writing traditional data persistence programs like SQL.
 
Whereas Spring Data JPA is a JPA Data Access Abstraction used to significantly reduce the amount of boilerplate code required to implement data access layers for various persistence stores. With Spring Data, we still need to use Hibernate, Eclipse Link, or any other JPA provider. One of the key benefits is that we can control transaction boundaries with the use of @Transactional annotation.
Caching is a mechanism that helps in reducing roundtrip calls to Database, REST service, files, etc. Performance under heavy load is a key feature expected from any modern web and mobile application, hence caching is really vital to enhance the speed of fetching data.
 
Spring Boot provides a starter project for caching “spring-boot-starter-cache”, adding this to an application brings in all the dependencies to enable JSR-107 (JCACHE - Java Temporary Caching API) and Spring caching annotations.
 
In order to enable caching in a Spring Boot application, we need to add @EnableCaching to the required configuration class. This will automatically configure a suitable CacheManager to serve as a provider for the cache.
 
Example :
 
@Configuration
@EnableCaching
public class CachingConfig {
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("addresses");
}
}
 
Now to enable caching, we need to add a @Cacheable annotation to the methods where we want to cache the data.
 
@Cacheable("addresses")
public String getAddress(Customer customer) {...}

 

HATEOAS (Hypermedia as the Engine of Application State) is a principle for REST APIs, according to which the API should guide the client through the application by returning relevant information about potential subsequent steps, along with the response.
 
This information is in the form of hypermedia links included with responses, which helps the client to navigate the site's REST interfaces. It essentially tells the clients what they can do next, and what is the URI of the resource. If a service consumer can use the links from the response to perform transactions, then it would not need to hardcode all links.
 
According to the Richardson Maturity Model, HATEOAS is considered the final level of REST.
 
To support HATEOAS, each resource in the application should contain a "links" property which defines hyperlinks to related resources. 
 
Each link object typically includes the following properties :
 
* "rel”: Relation with the target resource.
 
* "href”: URI for resource
 
For example :
{
 "contractId": 10067,
 "description": "Contract details for the requested orderId",
 "status": "created",
 "links": [
 {
"rel": "self",
    "href": "http://demoApplication.com/contracts/10067"}]
 }

 

Spring Cloud Contract implements the Consumer Driven Contracts (CDC) approach via the 'Spring Cloud Contract Verifier' project.
 
Consumer Driven Contracts is a software development and evolution approach where each consumer of service develops a contract that contains the consumer's expectations about the APIs provided by Service. The full collection of all of the consumers' contracts constitutes the requirement set for the service.
 
Once the service owners have all of the contracts for their consumers, the service owners can develop a test suite that verifies the service APIs. This test suite provides rapid feedback about failures when the service changes.
 
In Spring Cloud Contract, a "producer" is the owner of an API and a "consumer" is the user of an API.
 
Service A (as a consumer) creates a contract that service B (as a producer) will have to abide by. This contract acts as the invisible glue between services - even though they live in separate code bases and run on different JVMs. Breaking changes can be detected immediately during build time.
Yes, example for ReadOnly as true in Transaction Management is :
 
Suppose you have a scenario where you have to read data from your database like if you have a STUDENT database and you have to read the student details such as studentID, and studentName.
 
 So in such scenarios, you will have to set read-only on the transaction.
Spring Boot supports log4j2 for logging configuration. what all you have to do is you have to exclude log backfile and include log4j2 for logging.  You can do it by using the spring starter projects.
First configure mysql in your spring boot application.
 
Then you can map your entities with your db tables using JPA.
 
And with the help of save() method in JPA, you can directly insert your data into your database.
 
@RestController
@RequestMapping("/greatleasrning")
public class Controller {
@Autowired
private final FreeTimeLearningRepository freetimeLearningRepository;
public Controller(GreatLearningRepository freetimeLearningRepository) {
this. freetimelearningRepository = freetimeLearningRepository;
}
 
In the above case, your data which may be in JSON format can be inserted successfully into the database.
 
@RequestMapping(method = RequestMethod.POST)
ResponseEntity<?> insert(@RequestBody Course course) {
freetimeLearningRepository.save(course);
return ResponseEntity.accepted().build();
}
}

 

In order to use crud repository in spring boot, all you have to do is extend the crud repository which in turn extends the Repository interface as a result you will not need to implement your own methods.
 
Create a simple spring boot application which includes below dependency:
spring-boot-starter-data-jpa, spring-boot-starter-data-rest
 
And extend your repository interface as shown below :
 
package com.freetimelearning;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource
public interface GreatLearning extends CrudRepository<Candidate, Long> 
{
public List<Candidate> findById(long id);
 
//@Query("select s from Candidate s where s.age <= ?")
public List<Candidate> findByAgeLessThanEqual (long age);
}

 

Spring Boot Maven plugin provides Spring Boot support in the maven. This plugin provides options to create an executable jar or war files. Here are goals for this plugin.
 
* boot:run runs your Spring Boot application.
* spring-boot:repackage repackages your jar/war to be executable.
* spring-boot:start and spring-boot:stop to manage the lifecycle of your Spring Boot application (i.e. for integration tests).
* spring-boot:build-info generates build information that can be used by the Actuator.

To include this plugin in your project, add XML in the plugins section of your pom.xml
 
<plugins>
	<plugin>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-maven-plugin</artifactId>
		<version>2.0.5.RELEASE</version>
		<executions>
			<execution>
				<goals>
					<goal>repackage</goal>
				</goals>
			</execution>
		</executions>
	</plugin>
</plugins>

 

Use the server.ssl.* properties in the application.properties or yml file to configure and enable SSL for your Spring Boot application. Here are typical SSL configurations for your application.
 
server.port=8443 //SSL port
server.ssl.key-store=classpath:keystore.jks //You can also configure it to external location
server.ssl.key-store-password= //password for your key
server.ssl.key-password=//key password
 
Remember, Spring Boot does not support configuration of both HTTP and HTTPS through the property file. Configure other port programmatically if you need to use both ports.