Top 50 Spring Boot Interview Questions And Answers

Table of Contents

1.  What is Spring Boot?

Spring boot is a spring module framework for RAD build using Spring framework with the extra support of auto-configuration and embedded application server (like tomcat, jetty).

Spring Boot Interview Questions And Answers

2. What are the advantages of using Spring Boot?

  • It provides autoconfiguration to load a set of default configurations for a quick start of the application. 
  • Creates stand-alone applications with a range of non-functional features that are common to large classes of projects.
  • Spring boot comes with embedded tomcat, servlet containers jetty to avoid the usage of WAR files. 
  • Spring boot provides an opinionated view to reduce the developer effort and simplify maven configurations
  • Provides CLI tool to develop and test applications
  • Comes with spring boot starters to ensure dependency management and also provides various security metrics 
  • Consists of a wide range of APIs for monitoring and managing applications in dev and prod
  • Integrates with Spring Ecosystem like spring JDBC, Spring ORM, Spring Data, Spring security easily by avoiding boilerplate code

3. What is an IOC container and its advantages?

The spring IOC container(Inversion of control) is at the core of the spring framework. This container will read the configuration file and based on that it will create and store the objects and manage it. 

Advantage: Developers can concentrate on business logic since object creation and managing are handled by IOC containers. 

IOC container

4. Can we change the port of the embedded Tomcat server in Spring boot?

Yes we can change the port of the embedded tomcat server by using the application properties file.

In this file, you had 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 to the application. 

See also  Top 100 SAS Interview Questions And Answers

5. Can we override or replace the Embedded tomcat server in Spring Boot?

Yes, we can replace the embedded tomcat server by using the starter dependencies. Like spring-boot-starter-jetty as a dependency for each project as you need.

6. Can we disable the default web server in the Spring boot application?

The major strong point in Spring is to provide flexibility to build your application loosely coupled. Spring provides features to disable the webserver in a quick configuration. Yes we can use the application properties to configure the web application type i.e, spring.main.web-application-type=none. 

7. How to disable a specific auto-configuration class?

You can use the exclude attribute of @EnableAutoConfiguration, if you find any specific auto-configuration classes that you do not want are being applied. 

  • //By using “exclude” 
  • @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

8. What does the @SpringBootApplication annotation do internally?

As per the Spring Boot doc, 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 provides loosely coupled features that we can use for each individual annotation as per our project needs. 

9.  How to use a property defined in application.properties file into your java class?

Use the @Value annotation to access the properties which are defined in the application – properties file.

  • @Value(“${custom.value}”)
  • Private String custom Val;

10. Explain @RestController annotation in Spring Boot?

@RestController is a convenience annotation for creating Restful controllers. It is a specialization of @Component and is autodetected through classpath scanning. It adds the @Controller and @ResponseBody annotations. It converts the response to JSON or XML.

  • Which eliminates the need to annotate every request handling method of the controller class with the @ResponseBody annotation. It is typically used in combination with annotated handler methods based on the @RequestMapping annotation. 
  • Indicates that the data returned by each method will be written straight into the response body instead of rendering template.

Top Spring Boot Interview Questions And Answers

11. Difference between @RestController annotation and @Controller in Spring Boot? 

@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 into HTTP response as JSON or XML.  

12. What is the difference between RequestMapping and GetMapping?

RequestMapping can be used with GET, POST,PUT, and many other requests methods using the method attribute on annotation. Whereas GetMapping is only an extension of RequestMapping, which helps you to improve clarity on requests.

13. What is the use of Profiles in spring boot?

When developing applications for the enterprise, we typically deal with multiple environments such as Dev, QA, and Prod. The configuration properties for these environments are different. 

For example, we might be using an embedded H2 database for Dev, but Prod could have the proprietary Oracle or DB2. Even if the DBMS is the same across environments, the URLs would definitely be different.

Spring has the provision of profiles, to help separate the configuration for each environment. So that instead of maintaining this programmatically, the properties can be kept in separate files such as application-dev.properties and application-prod.properties. 

The default application.properties point to the currently active profile using spring.profiles.active so that the correct configuration is picked up. 

14. What is the difference between spring and spring boot?

SpringSpring Boot
A web application framework based on JavaA module of Spring 
Provides tools and libraries to create customized web applicationsUsed to create a Spring application project which can just run/execute 
Spring is more complex than Spring BootSpring Boot is less complex than the Spring framework
Takes an non-opinionated view   Takes an opinionated view of a platform

15. Mention a few features of Spring Boot.

few features of Spring Boot
  • Spring CLI: Spring Boot CLI allows you to use Groovy for writing Spring boot applications and avoids boilerplate code.  
  • Spring Initializer: This is basically a web application, which can create an internal project structure for you.
  • Spring Actuator: This feature provides help while running Spring Boot applications.
  • Starter Dependency: With the help of this feature, Spring Boot aggregates common dependencies together and eventually improves productivity. 
  • Auto-configuration: The auto-configuration features of Spring Boot helps in loading the default configurations according to the project you are working on.
  • Logging and Security: This feature of Spring Boot, ensures that all the applications made using Spring Boot are properly secured without any hassle. 

16. Explain how to create Spring Boot applications using Maven. 

There are various approaches to create a Spring Boot application using maven:

  • Spring Boot CLI
  • Spring Boot Project Wizard
  • Spring Boot Initializer 
  • Spring Maven Project 

17.  Mention the possible sources of external configuration.

The most possible source of external configuration:

  • Application properties
  • Command line properties 
  • Profile specific properties

18. Can you explain what happens in the background when a Spring Boot application is “Run as Java Application”?

When a Spring Boot application is executed as “Run as Java application”, then it automatically launches up the tomcat server as soon as it sees that you are developing a web application. 

19. What are the Spring Boot starters and what are the available starters? 

Spring Boot starters are a set of convenient dependency management providers which can be used in the application to enable dependencies. These starters make development easy and rapid. All the available starters come under the org.springframework.boot group. 

  • Spring-boot-starter
  • Spring-boot-starter-jdbc
  • Spring-boot-starter-web
  • Spring-boot-starter-data-jpa
  • Spring-boot-starter-security
  • Spring-boot-starter-aop
  • spring-boot-starter-test
See also  Top 100 SAS Interview Questions And Answers

20. Explain spring actuator and its advantages. 

Spring actuator is a feature of Spring Boot with the help of which you can see what is happening inside a running application.

The Spring actuator provides a very easy way to access the production-ready REST points and fetch all kinds of information from the web.

These points are secured using Spring Security’s content negotiation strategy.

Top Spring Boot Interview Questions And Answers

21. What is Spring Boot dependency management? 

Spring Boot dependency management is used to manage dependencies and configuration automatically without you specifying the version for any of those dependencies. 

22. Mention the minimum requirements for a Spring Boot System. 

Spring Boot 2.1.7. Release requires

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 

23. What is thymeleaf and how to use thymeleaf? 

Thyme leaf is a server-side Java template engine used for web applications.

It aims to bring a natural template for your web application and can integrate as well with Spring Framework and HTML5 Java web applications. 

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

What is thymeleaf

24. What is the need of spring Boot DevTools? 

Spring Boot DevTools is an elaborated set of tools and aims to make the process of developing an application easier. 

If the application runs in production, then this module is automatically disabled, repackaging of archives is also excluded by default. 

So, the Spring Boot Developer Tools applies properties to the respective development environments. 

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
spring Boot DevTools

25. Mention the steps to create a Spring Boot project using Spring Initializer. 

Spring Initializer is a web tool provided by Spring. With the help of this tool, you can create Spring Boot projects by just providing project details.

  • Choose the maven project and the required dependencies. Then, fill the other required details like Group, Artifact, and then click on Generate Project.
  • Once the project is downloaded, extract the project onto your system. 
  •  Next, you have to import this project using the import option on the Spring Tool Suite IDE.

26. Mention the steps to connect Spring Boot application to a database using JDBC. 

Spring Boot starter projects provide the required libraries to connect the application with JDBC.

So, for example, if you just have to create an application and connect it with MYSQL database, you can follow the below steps:

Step 1: Create a database in MySQL

CREATE DATABASE example;

Step 2: Create a table inside this database

CREATE TABLE customers(customerid INT PRIMARY KEY NOT NULL AUTO_INCREMENT, customername VARCHAR (255));

Step 3: Create a Spring Boot project and provide the required details

Step 4: Add JDBC, MySQL and web dependencies

Step 5: Once the project is created, you have to configure the database into application properties.

spring.datasource.url=jdbc:mysql://localhost:3306/example
spring.datasource.username=root
spring.datasource.password=mysql
spring.jpa.hibernate.ddl-auto=create-drop

Step 6: The main application.java class should have the following code:

package com.edureka;
import org.springframework.boot.SpringApplication;import
org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleApplication {public static void main(String[ ] args) {
SpringApplication.run(SampleApplication.class,args);
 }
}

Step 7: You have to create a controller to handle the HTTP requests, by mentioning the following code:

package com.softtest;
Import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RestController;
@RestController 
Public class JdbcController {
@Autowired 
JdbcTemplate jdbc;
@RequestMapping(“/insert”)
Public String index(){
jdbc.execute(“insert into customer(name)values(‘Abdul’)”);
return “Data Entry Successful”;
}
} 

Step 8: Finally execute this project as a Java application. 

Step 9: Open the URL [localhost:8080/insert], and you will see the output as data entry successful. 

You can also go forward and check if the data is entered into the table.

27. How to enable HTTP/2 support in Spring Boot? 

You can enable the HTTP/2 support in Spring Boot by:

server.http2.enabled=true

28. What are the @RequestMapping and @RestController annotations in Spring Boot used for? 

@RequestMapping@RestController
This annotation is used to provide the routing information and tells Spring that any HTTP request must be mapped to the respective method. This annotation is used to provide the routing information and tells Spring that any HTTP request must be mapped to the respective method.
To use this annotation, you have to import org.springframework.web.bind.annotation.RequestMapping; To use this annotation, you have to import org.springframework.web.bind.annoation.RequestMapping;

Consider you have a method example() which should map with /example URL.

package com.softtest;
Import
org.springframework.web.bind.annotation.RequestMapping;
Import
org.springframework.web.bind.annotation.RestController;
@RestController 
public class SampleController {
@RequestMapping(“/example”)  
public class SampleController {
@RequestMapping(“/example”)
public String example() {
return “Welcome To Soft Test” ;
}
}

29. What is Spring Boot CLI and how to execute the Spring Boot project using boot CLI?  

Spring Boot CLI is a tool supported by the official Spring Framework. The steps to execute a Spring Boot project are as follows:

  • Download the CLI tool from the official site and extract the zip file. The bin folder present in the Spring setup is used to execute the Spring Boot application.
  • Since Spring Boot CLI executes groovy files, you need to create a groovy file for Spring Boot application. So, to do that, open the terminal and change the current directory to the bin folder. 

Create a controller as follows:

@RestController       public class Sample  {
  @RequestMapping( “/example” )
   String index() {
<h1>”Welcome To Soft Test”</h1>;
}       }
Execute the groovy file by mentioning 
. /spring run Sample.groovy;

30. What are the differences between JPA and Hibernate?  

JPAHibernate
It is a Data Access Abstraction used to reduce the amount of boilerplate code   It is an implementation of Java Persistence API and offers benefits of loose coupling 

Top Spring Boot Interview Questions And Answers

31. How can we create a custom endpoint in Spring Boot Actuator? 

To create a custom endpoint in Spring Boot 2.x, you can use the @Endpoint annotation.

See also  Top 100 SAS Interview Questions And Answers

Spring Boot also exposes endpoints using @WebEndpointor, @WebEndpointExtension over HTTP with the help of Spring MVC, Jersey etc.

32. What do you understand about Spring Data? 

Spring data aims to make it easy for developers to use relational and non-relational databases, cloud-based data services, and other data access technologies.

So, basically, it makes it easy for data access and still retains the underlying data.

33. What do you understand about auto-configuration in Spring Boot? 

Auto-configuration is used to automatically configure the required configuration for the application. 

For example, if you have a data source bean present in the classpath of the application, then it automatically configures the JDBC template. 

With the help of auto-configuration, you can create a Java application in an easy way, as it automatically configures the required beans, controllers etc. 

34. What are the differences between @SpringBootApplication and @EnableAutoConfiguration annotation? 

SpringBootApplicationEnableAutoConfiguration
Used in the main class or bootstrap classUsed to enable auto-configuration and component scanning in your project
It is a combination of @Configuration, @ComponentScan and @EnableAutoConfiguration annotationsIt is a combination of @Configuration and @ComponentScan annotations

35. What are the steps to deploy Spring Boot web applications as JAR and WAR files? 

To deploy a Spring Boot web application, you just have to add the following plugin in the pom.xml file, just add a plugin element to pom.xml:

@<plugin>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

36. Can you give an example for ReadOnly as true in Transaction management?  

Consider a scenario, where you have to read data from the database. 

For example, let us say you have a customer database, and you want to read the customer details such as customerID, customername, and customeremailID. 

To do that you will set read-only on the transaction as we do not want to check for the changes in the entities. 

37.  Can you explain how to deploy to a different server with Spring Boot?  

To deploy a different server with Spring Boot, follow the below steps: 

  • Generate a WAR from the project
  • Deploy the WAR file on to your favourite server 

38. What is the best way to expose custom application configuration with Spring Boot? 

One way to expose the custom application configuration in Spring Boot is by using the @Value annotation.  

But, the only problem with this annotation is that all the configuration values will be distributed throughout the application. 

Instead, you can use a centralized approach. 

By centralized approach, I mean that you can define a configuration component using the @ConfigurationProperties as follows:  

<packaging>@Component
@ConfigurationProperties(“example”)
public class SampleConfiguration {
private int num;
private boolean value;
private String msg;</packaging>

According to the above snippet, the values configured in application.properties will be as follows:

example.num: 100

example.value: true

example.msg: Dynamic message 

39. Can we create a non-web application in Spring Boot? 

Yes, we can create a non-web application by removing the web dependencies from the classpath along with changing the way Spring Boot creates the application context. 

40. What are the steps to connect an external database like MySQL or Oracle? 

To connect an external database, you have to follow the below steps:

  • Start by adding the dependency for MySQL Connector to pom.xml
  • Then remove H2 Dependency from pom.xml 
  • Now, set up your MySQL database and configure your connection to the MySQL database
  • Restart your project 

Top Spring Boot Interview Questions And Answers

41. Mention the advantages of YAML file than Properties file and the different ways to load YAML file in Spring boot.

The advantage of the YAML file over 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 files 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 

42. How is Hibernate chosen as the default implementation for JPA without any configuration?  

When we use the Spring Boot Auto Configuration, automatically the spring-boot-starter-data-jpa dependency gets added to the pom.xml file.

Now, since this dependency has a transitive dependency on JPA and Hibernate, Spring Boot automatically auto-configures Hibernate as the default implementation for JPA, whenever it sees Hibernate in classpath. 

43. What do you understand about Spring Data REST?  

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> {
To expose the REST services, you can use the POST method in the following way:
{
“customerid”: “Rohit”,
“customeremailid”: “[email protected]”
}
Response Content:
{
“customerid”: “Rohit”,
“customermailid” : “[email protected]”,
“_links”:  {
“self”:  {
“href”: “http://localhost:8080/sample/1”
} ,
“sample” : {
“href” : “http://localhost:8080/sample/1”
} }

44. In which layer, should the boundary of a transaction start? 

The boundary of the transaction should start from the Service Layer since the logic for the business transaction is present in this layer itself. 

45.  What does path=”sample”, collectionResourceRel=”sample”work with Spring Data Rest?  

@RepositoryRestResource(collectionResourceRel = “sample” , path = “sample” )
public interface SampleRepository extends 
PagingAndSortingRepository<Sample, Long>
  • path – This section is used to mention the segment under which the resource is to be exported. 
  • collectionResourceRel: This value is used to generate links to the collection resource.

46. Explain how to register a custom auto-configuration. 

In order to register an auto-configuration class, you have to mention the fully-qualified name under the @EnableAutoConfiguration key META-INF/spring.factories file.

Also if we build with maven, then this file should be placed in the resources/META-INT directory. 

47. How do you Configure Log4j for logging? 

Since Spring Boot supports Log4j2 for logging a configuration, you have to exclude Logback and include Log4j2 for logging. This can be only done if you are using the starters project. 

48.  Mention the differences between WAR and embedded containers. 

WAREmbedded Containers
WAR benefits a considerable measure from Spring Boot Only one component of Spring Boot is during improvements 

49. What are the steps to add a custom JS code with Spring Boot? 

The steps to add a custom JS code with Spring Boot are as follows:

  • Create a folder called static under the resource folder 
  • In this folder, you can put the static content in the folder

Note: Just in case, the browser throws an unauthorized error, you either disable the security or search for the password in the log file, and eventually pass it in the request header. 

50. How to instruct an auto-configuration to back off when a bean exists? 

To instruct an auto-configuration class to back off when a beam exits, you have to use the @ConditionalOnMissingBean annotation. 

The attributes of this annotation are as follows:

  • value: This attribute stores the type of beans to be checked
  • name: This attribute stores the name of beans to be checked