Spring boot Interview Question And Answer


Spring boot, a Java-based framework, is widely used to create microservices. The developers use Microservice, an architecture, to develop and deploy services independently. With the help of spring boot, a user can create a stand-alone and production-grade spring application more quickly. Moreover, there is no need for an entire Spring configuration setup.

A Java developer must know some basic Spring boot interview questions as it helps them with multiple things. By using spring boot, you can effortlessly avoid complex XML configurations in Spring. Also, users get a simple path to configure Java Beans and Database Transactions. It also supports embedded containers, Tomcat, Undertow, and Jetty.

Some advantages of spring boots are as below:

  • It uses JavaConfig instead of XML
  • It provides users with an opinionated development approach.
  • You get starter projects or defaults for agile development.
  • There is no need for a separate web server.

Features

Features that you must know if you want to prepare for Spring Boot interview questions efficiently:

  • Starter dependency: Spring boot framework includes many dependencies. The starter dependence feature helps it to aggregate them together. Moreover, you get other starters such as Test Starter, Web Starter, Mail Starter, and more, increasing productivity.

For example, you need to add this starter dependency in the project-spring-boot-starter-data-jpa if you want to use JPA and Spring for database access.

  • Auto-Configuration: A vital feature that scans the classpath and searches the libraries/Jars in the classpath. Therefore, this feature gives you the necessary configuration for designing and running the application.

For example, this feature will automatically align the Thymeleaf template resolver and other settings if Thymeleaf.jar is present in the classpath while designing an application with it.

  • Spring Initializer: With this web application, you can create the early project structure and build scripts without hassle during the project setup. This feature drastically decreases development time, and your productivity increases exponentially.
  • Spring Actuator: Spring actuator is another critical feature for microservices as they enable deployment. It includes built-in management endpoints, secured by default. 

Here for example, you get /beans which exhibits the whole list of all Spring beans in the application. Another example is /health, which monitors the production of a system and displays application health information.

  • Spring CLI: With Spring CLI, developers can write the application in a more concise code using Groovy. 

1 . What is Spring Boot and mention the need for it?

It is a Spring module that aims to simplify the use of the Spring framework for Java development. It is used to create stand-alone Spring-based applications that you can just run. So, it basically removes a lot of configurations and dependencies. Aiming at the Rapid Application Development, Spring Boot framework comes with the auto-dependency resolution, embedded HTTP servers, auto-configuration, management endpoints, and Spring Boot CLI.

So, if you ask me why should anybody use it, then I would say, it not only improves productivity but also provides a lot of conveniences to write your own business logic.

2 . Mention the advantages

The advantages of Spring Boot are as follows:

  • Provides auto-configuration to load a set of default configuration 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
  • It comes with embedded tomcat, servlet containers jetty to avoid the usage of WAR files
  • It provides an opinionated view to reduce the developer effort and simplify maven configurations
  • Provides CLI tool to develop and test applications
  • Comes with 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 Ecosystems like Spring JDBC, Spring ORM, Spring Data, Spring Security easily by avoiding boilerplate code.

3 . Mention a few features of Spring Boot.

  1. Spring CLI – Spring Boot CLI allows you to use Groovy for writing Spring boot applications and avoids boilerplate code.
  2. Starter Dependency – With the help of this feature, it aggregates common dependencies together and eventually improves productivity
  3. Auto-Configuration – The auto-configuration feature helps in loading the default configurations according to the project you are working on. In this way, you can avoid any unnecessary WAR files.
  4. Spring Initializer – This is basically a web application, which can create an internal project structure for you. So, you do not have to manually set up the structure of the project, instead, you can use this feature.
  5. Spring Actuator –  This feature provides help while running applications.
  6. Logging and Security – The logging and security feature, ensures that all the applications made using Spring Boot are properly secured without any hassle.

 4 . Explain how to create a Spring Boot application using Maven.

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

5 . Mention the possible sources of external configuration.

There is no doubt in the fact that it 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, it 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 – it 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.

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

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

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

Spring Boot starters are a set of convenient dependency management providers that 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. Few of the popular starters are as follows:

  • spring-boot-starter: – This is the core starter and includes logging, auto-configuration support, and YAML.
  • spring-boot-starter-jdbc – This starter is used for HikariCP connection pool with JDBC
  • spring-boot-starter-web – Is the starter for building web applications, including RESTful, applications using Spring MVC
  • spring-boot-starter-data-jpa – Is the starter to use Spring Data JPA with Hibernate
  • spring-boot-starter-security – Is the starter used for Spring Security
  • spring-boot-starter-aop: This starter is used for aspect-oriented programming with AspectJ and  Spring AOP
  • spring-boot-starter-test: Is the starter for testing Spring Boot applications

8 . Explain Spring Actuator and its advantages- Spring boot interview question

Spring Actuator is a cool feature with the help of which you can see what is happening inside a running application. So, whenever you want to debug your application, and need to analyze the logs you need to understand what is happening in the application right? In such a scenario, the Spring Actuator provides easy access to features such as identifying beans, CPU usage, etc. 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.

9 . What is Spring Boot dependency management?

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

10 . Mention the minimum requirements for a System.

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

11 . Explain what is thymeleaf and how to use thymeleaf?

Thymeleaf 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 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>

12 . Can we change the port of the embedded Tomcat server?

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 and the required configurations will be applied on to the application.

13 . What is the need for DevTools?

Spring Boot DevTools 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 is 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>


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

Spring Initializr is a web tool provided by Spring. With the help of this tool, you can create Spring Boot projects by just providing project details. The following steps need to be followed to create a Spring Boot project using Spring Initializer:

  • Choose the maven project and the required dependencies. Then, fill in 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
  • While importing the project, remember that you have to choose the project type to be Maven and the source project should contain the pom.xml file.

Once all the above steps are followed you will see that the Spring Boot project is created with all the required dependencies.

15 . 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

1CREATE DATABASE example;

Step 2: Then you have to create a table inside this database.

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

Step 3: Now, create a Spring Boot project and provide the required details

Step 4: Add the 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=edureka 
spring.jpa.hibernate.ddl-auto=create-drop 


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

package interviewpitch; 
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);     } }

Next, you have to create a controller to handle the HTTP requests, by mentioning the following code:

package com.edureka;
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 customers(name)values('Aryya')");
return "Data Entry Successful";
}
}

Finally, execute this project as a Java application.

Step 9: Next, 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.

16 . How to enable HTTP/2 support?

You can enable the HTTP/2 support in Spring Boot by: server.http2.enabled=true

17 . 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 add the @ResponseBody and @Controller annotation to the class
o 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.annotation.RestController;

18 . 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 terminal and change the current directory to the bin folder. Now, open a groovy file (for example Sample.groovy)
  • In this file create a controller as follows:
@RestController  public class Sample {  
 @RequestMapping("/example")  
 String index(){  
<h1>"Welcome To Edureka"</h1>;  
}  }
Then execute the groovy file by mentioning:
1
./spring run Sample.groovy;


Once, the project is executed go to the URL(localhost:8080:/example) and you will see the output as Welcome To Edureka

19 . Mention the differences between JPA and Hibernate.

JPA is a Data Access Abstraction used to reduce the amount of boilerplate code while as Hibernate is an implementation of Java Persistence API and offers benefits of loose coupling.

20 . 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. Spring Boot also exposes endpoints using @WebEndpointor, @WebEndpointExtension over HTTP with the help of Spring MVC, Jersey, etc.

21 . Explain Spring Data.

Spring Data aims to make it easy for the 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.

22 . What do you understand about auto-configuration in Spring Boot and how to disable the auto-configuration?

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. 

To disable the auto-configuration property, you have to exclude the attribute of @EnableAutoConfiguration, in the scenario where you do not want it to be applied.

1@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

If the class is not on the classpath, then to exclude the auto-configuration, you have to mention the following code:

2@EnableAutoConfiguration(excludeName={Sample.class})

Apart from this, it also provides the facility to exclude list of auto-configuration classes by using the spring.autoconfigure.exclude property. You can go forward, and add it either in the application.properties or add multiple classes with comma-separated.

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

@SpringBootApplication@EnableAutoConfiguration
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 annotations.It is a combination of @Configuration and @ComponentScan annotations

24 . 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:

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


By using the above plugin, you will get a JAR executing the package phase. This JAR will contain all the necessary libraries and dependencies required. It will also contain an embedded server. So, you can basically run the application like an ordinary JAR file.

Note: The packaging element in the pom.xml file must be set to jar to build a JAR file as below:

1<packaging>jar</packaging>

Similarly, if you want to build a WAR file, then you will mention

2<packaging>war</packaging>

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

Example for ReadOnly as TRUE in transaction management could be as follows:

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, and customername. To do that, you will set read-only on the transaction as we do not want to check for the changes in the entities.

26 . 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
  • Then, deploy the WAR file onto your favorite server

Note: The steps to deploy the WAR file on the server is dependent on the server you choose.

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

One way to expose the custom application configuration 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:

@Component
@ConfigurationProperties("example")
public class SampleConfiguration {
private int number;
private boolean value;
private String message;


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

example.number: 100
example.value: true
example.message: Dynamic Message

28 . 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 it creates the application context.

29 . 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

30 . Mention the advantages of the YAML file than Properties file and the different ways to load YAML file.

The advantages 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 file as an alternative to properties whenever you use the SnakeYAML library on your classpath. The different ways to load a YAML file here is as follows:

  • Use YamlMapFactoryBean to load YAML as a Map
  • Use YamlPropertiesFactoryBean to load YAML as Properties

31 . 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, it automatically auto-configures Hibernate as the default implementation for JPA, whenever it sees Hibernate in the classpath. 

32 . What is the difference between RequestMapping and GetMapping?

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/*”}

33 . 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.

34 . What is Spring vs Spring Boot?

Being able to explain the differences between these two terms can demonstrate to the interviewer that you are well-versed in this resource. Consider explaining one term first and then the other to keep your answer organised.

Example: “Spring is a framework for web applications. The framework has tools and libraries that you can use to create custom applications. Spring Boot is a module of Spring that you can use to create a Spring application or project that can only run.”

35 . Discuss the advantages of using Spring Boot.

You can use this question to showcase the benefits you have experienced when using Spring Boot. Use the STAR method to explain a situation in which you used Spring Boot, the task you had to complete, the actions you took using Spring Boot and the results and benefits you gained.

Example: “There are several advantages of it, including ease of use. It also helps reduce the time and resources required for creating microservices, which increases your overall profitability. In my experience, I used it to convert ChemCal Corp to microservices architecture. I handled all aspects of development, and using Spring Boot’s autoconfigured starters allowed me to do this quickly and resource efficiently.”

36 . How do you set up a Spring Boot project?

This is a technical question that tests your knowledge of Spring Boot basics. A simple step process can provide a clear and concise answer to the question.

Example: “There are several ways to set up a project. One way is to use the Spring Initials with Eclipse and Maven. First, launch the Initializr and choose the Group, Artifact and dependencies. Then, select Generate Project. Finally, you can choose to import your existing Maven project from Eclipse.”

37 . What is autoconfiguration?

This question is related to one of Spring Boot’s more important features, autoconfiguration. This feature makes it an attractive option for developers. So in a interview, you might be expected to define autoconfiguration thoroughly.

Example: “Autoconfiguration is an important feature that was created out of a need to reduce the complexity of configuration in the framework. Autoconfiguration does this by offering different starters, and depending on which starter you use, it configures the application differently. This saves developers time and makes Spring Boot easier to use than Spring.”

38 . How do you disable autoconfiguration in Spring Boot?

Because autoconfiguration is the default of Spring Boot, you may need to know how to turn it off. In your answer, explain how to the disable feature without having to write code. Keep in mind, some questions may ask you to write or read code and interpret it, and you should be prepared to do that too.

Example: “The exclude feature of the @EnableAutoConfiguration annotation allows you to disable autoconfiguration. Do this by using it within an applicable string of code.”

39 . What is the process of registering a custom autoconfiguration with Spring Boot?

This question assesses your understanding of the basic functionality of it. However, bring with you a portfolio of Spring Book coding, if you have one, to display and demonstrate your knowledge of reading and writing code in the system, too.

Example: “Custom autoconfiguration is a class that can be registered. To do this, the full name of the autoconfiguration should be entered into the META-INF/spring.factories file in the EnableAutoConfiguration key. However, if it is in Maven, it should be registered in the Maven directory file.”

40 . Can you list the available Spring Boot starters?

Spring Boot starters are the autoconfigured tools from which you base your microservices application. To answer this question, memorise and recall the starters. Then, consider listing other related items, like dependencies, key features and project options.

Example: “Some common starters are spring-boot-starter, spring-boot-starter-aop and spring-boot-starter-data-jpa. Spring-boot-starter is a core starter that has autoconfiguration support and more. Spring-boot-starter-aop is used for aspect-oriented programming, and spring-boot-starter-data-jpa is compatible with Hibernate. These are a few top starters, although there are more depending on your use case.”

41 . Explain your experience with Spring Boot.

Successfully answering this question means coming prepared to discuss a time you developed and implemented microservices, especially if you did so using Spring Boot.

Example: “I have four years of experience using Spring Boot to resolve bandwidth issues as my company scaled to more users on its proprietary software platform.”

42 . What are the most important skills for a Spring Boot programmer to have?

This question assesses your understanding of the vital abilities needed to use it effectively. It also encourages you to explain which of these abilities you have and how you excel at using them. Some skills you can describe include architecture knowledge, DevOps and containerisation skills, domain modelling, testing and security.

Example: “I pride myself on a deep knowledge of architecture and am CompTIA Security+ certified. My ability to create microservices architecture securely is an asset to the companies where I may work.”

43 . 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 the with maven, then this file should be placed in the resources/META-INT directory.

44 . 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.

45 . What do you think is the need for Profiles?

Profiles are used to provide a way to segregate the different parts of the application configuration and make it available for various environments. So, basically, any @Component or a @Configuration can be marked with a @Profile to limit as it is loaded. Consider you have multiple environments,

  • Dev
  • QA
  • Stage
  • Production

Now, let’s say, you want to have different application configuration in each of the environments, you can use profiles to have different application configurations for different environments. So, basically, Spring and Spring Boot provide features through which you can specify:

  • The active profile for a specific environment
  • The configuration of various environments for various profiles.

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

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

  • Now, create a folder and name it static under the resources folder
  • In this folder, you can put the static content in that 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.

47 . Mention the differences between WAR and embedded containers

WAR benefits a considerable measure from Spring Boot while as Only one component of Spring Boot and is utilized during improvements.