- What is Spring Boot CLI? What are its benefits?
- What is the difference between an embedded container and a WAR?
- Mention the advantages of Spring Boot
- Mention the possible sources of external configuration
- What are the Spring Boot starters and what are the available starters?
- Can we change the port of the embedded Tomcat server in Spring boot?
- Mention the steps to create a Spring Boot project using Spring Initializr
- Can you give an example for ReadOnly as true in Transaction management?
- Can you explain how to deploy to a different server with Spring Boot?
- Mention the advantages of the YAML file than Properties file and the different ways to load YAML file in Spring boot.
- How is Hibernate chosen as the default implementation for JPA without any configuration?
- Explain how to register a custom auto-configuration.
- What are the steps to add a custom JS code with Spring Boot?
- Why is Spring Data REST not recommended in real-world applications?
- What do you understand by Spring Boot supports relaxed binding?
- Where is the database connection information specified and how does it automatically connect to H2?
- What is @RequestMapping annotation in Spring Boot?
- What is the difference between Spring and Spring Boot?
- How to Write Integration Tests?
- How to enable hot deployment and live reload on browser?
- What is a shutdown in the actuator?
- Is it possible to change the port of Embedded Tomcat server in Spring boot?
- Can we disable the default web server in the Spring Boot application?
- What are the various Advantages Of Using Spring Boot?
- What do Dev Tools in Spring boot mean?
- What does Spring Boot Starter Pom mean? Why Is It Useful?
- Why do we use “Opinionated” in spring boot?
- What are esteem properties of Spring Boot?
- How Might You Implement Spring Security In Spring Boot Application?
- Differentiate Between An Embedded Container And A War?
- Explain the difference between JPA and Hibernate?
- What does Aspect-Oriented Programming (AOP) mean?
- What is the difference between RequestMapping and GetMapping in Spring Boot?
- What is JavaConfig?
- How to implement JWT authentication for Spring Boot Application?
- How to disable Actuator endpoint security in Spring Boot?
- Have you integrated Spring Boot and ActiveMQ?
- How to implement Pagination and Sorting with Spring Boot?
- What is Swagger? Have you implemented it using Spring Boot?
- What is Spring Batch? How do you implement it using Spring Boot?
- What is FreeMarker Template? How do you implement it using Spring Boot?
- What is caching? Have you used any caching framework with Spring Boot?
- What is CSRF attack? How to enable CSRF protection against it?
- When will you use WebSockets? How tto implement it using Spring Boot?
- What is AOP? How to use it with Spring Boot?
- How can we monitor all the Spring Boot Microservices?
- Explain thymeleaf in Spring Boot.
- Can you disable the default web server in the Spring Boot application?
- What is Swagger2?
- What are the major benefits of spring Externalized Configuration?
- Define ELK stack.
- Explain CORS in Spring Boot?
- Explain different types of dependency injection.
- What are the advantages of micro services?
- What is join point in Spring Boot?
- List out benefits of using the JavaConfig method.
- What are disadvantages of Spring boot?
Spring Boot Interview Questions and Answers (2023)
In this post, we have put together Spring Boot interview questions and answers for beginner, intermediate and experienced candidates. These questions are categorized for quick browsing before the interview or to act as a detailed guide on different topics in Spring Boot for interviewers.
General
What is Spring Boot CLI? What are its benefits?
View answer
Spring Boot CLI is a command line interface which allows you to create Spring-based Java application using Groovy. Since it's used Groovy, it allows you to create Spring Boot application from the command line without ceremony e.g. you don't need to define getter and setter method, or access modifiers, return statements etc.
It's also very powerful and can auto-include a lot of library in Groovy's default package if you happen to use it. For example, if you use JdbcTempalte, it can automatically load that for you.
What is the difference between an embedded container and a WAR?
View answer
The main difference between an embedded container and a WAR file is that you can Spring Boot application as a JAR from the command prompt without setting up a web server. But to run a WAR file, you need to first set up a web server like Tomcat which has Servlet container and then you need to deploy WAR there.
Mention the advantages of Spring Boot
View answer
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
- 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.
Mention the possible sources of external configuration
View answer
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.
What are the Spring Boot starters and what are the available starters?
View answer
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. 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
Can we change the port of the embedded Tomcat server in Spring boot?
View answer
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.
Mention the steps to create a Spring Boot project using Spring Initializr
View answer
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 Initializr:
- 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. 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.
Can you give an example for ReadOnly as true in Transaction management?
View answer
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.
Can you explain how to deploy to a different server with Spring Boot?
View answer
To deploy a different server with Spring Boot: Generate a WAR from the project and then, deploy the WAR file onto your favorite server. The steps to deploy the WAR file on the server is dependent on the server you choose.
Mention the advantages of the YAML file than Properties file and the different ways to load YAML file in Spring boot.
View answer
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
How is Hibernate chosen as the default implementation for JPA without any configuration?
View answer
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 the classpath.
Explain how to register a custom auto-configuration.
View answer
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.
What are the steps to add a custom JS code with Spring Boot?
View answer
Create a folder and name it static under the resources folder and you can put the static content in that folder. 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.
Why is Spring Data REST not recommended in real-world applications?
View answer
Spring Data REST is not recommended in real-world applications as you are exposing your database entities directly as REST Services. While designing RESTful services, the two most important things that we consider is the domain model and the consumers. But, while using Spring Data REST, none of these parameters are considered. The entities are directly exposed. So, I would just say, you can use Spring Data REST, for the initial evolution of the project.
What do you understand by Spring Boot supports relaxed binding?
View answer
Relaxed binding, is a way in which, the property name does not need to match the key of the environment property. In Spring Boot, relaxed binding is applicable to the type-safe binding of the configuration properties. For example, if a property in a bean class with the @ConfigurationPropertie annotation is used sampleProp, then it can be bounded to any of the following environment properties:
- sampleProp
- sample-Prop
- sample_Prop
- SAMPLE_PROP
Where is the database connection information specified and how does it automatically connect to H2?
View answer
It is because of the Spring Boot auto-configuration that, configures the dependencies of the application. So, the database connection information, and automatically connecting the database to H2 is done by the auto-configuration property.
What is @RequestMapping annotation in Spring Boot?
View answer
The @RequestMapping annotation is used to provide routing information. It tells to the Spring that any HTTP request should map to the corresponding method. We need to import org.springframework.web.annotation package in our file.
What is the difference between Spring and Spring Boot?
View answer
The Spring Framework provides multiple features that make the development of web applications easier. These features include dependency injection, data binding, aspect-oriented programming, data access, and many more. Over the years, Spring has been growing more and more complex, and the amount of configuration such application requires can be intimidating. This is where Spring Boot comes in handy – it makes configuring a Spring application a breeze.
Essentially, while Spring is unopinionated, Spring Boot takes an opinionated view of the platform and libraries, letting us get started quickly.
Here are two of the most important benefits Spring Boot brings in:
- Auto-configure applications based on the artifacts it finds on the classpath
- Provide non-functional features common to applications in production, such as security or health checks
How to Write Integration Tests?
View answer
When running integration tests for a Spring application, we must have an ApplicationContext.
To make our life easier, Spring Boot provides a special annotation for testing – @SpringBootTest. This annotation creates an ApplicationContext from configuration classes indicated by its classes attribute.
In case the classes attribute isn't set, Spring Boot searches for the primary configuration class. The search starts from the package containing the test up until it finds a class annotated with @SpringBootApplication or @SpringBootConfiguration.
Notice if we use JUnit 4, we must decorate the test class with @RunWith(SpringRunner.class).
How to enable hot deployment and live reload on browser?
View answer
Most modern IDEs support hot swapping of bytecode and most code changes should reload cleanly with no side effects. Additionally, the spring-boot-devtools module includes support for automatic application restarts whenever files on the classpath change.
By default, any entry on the classpath that points to a folder is monitored for changes. Note that certain resources, such as static assets and view templates, do not need to restart the application.
The spring-boot-devtools module includes an embedded LiveReload server that can be used to trigger a browser refresh when a resource is changed. LiveReload browser extensions are freely available for Chrome, Firefox and Safari from livereload.com.
To enable/disable LiveReload server, change value of spring.devtools.livereload.enabled property to true (default value) or false.
What is a shutdown in the actuator?
View answer
Shutdown is an endpoint that allows the application to be gracefully shutdown. This feature is not enabled by default. You can enable this by using management.endpoint.shutdown.enabled=true in your application.properties file. But be careful about this if you are using this.
Is it possible to change the port of Embedded Tomcat server in Spring boot?
View answer
Yes, it's possible to change the port. You can use the application.properties file to change the port. But you need to mention "server.port" (i.e. server.port=8081). Make sure you have application.properties in your project classpath; REST Spring framework will take care of the rest. If you mention server.port=0 , then it will automatically assign any available port.
Can we disable the default web server in the Spring Boot application?
View answer
The major strong point in Spring is to provide flexibility to build your application loosely coupled. Spring provides features to disable the web server 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.
What are the various Advantages Of Using Spring Boot?
View answer
Here are some of the various advantages of using Spring Boot:
- It is quite easy to create Spring Based applications with Java or Groovy.
- It lessens lots of improvement time and expands profitability.
- It abstains from writing lots of standard Codes, Annotations, and XML Configuration.
- It is quite easy to coordinate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring Data, Spring Security and so forth.
- It takes after the "Opinionated Defaults Configuration" Approach to diminish Developer effort
- It gives Embedded HTTP servers like Tomcat, Jetty and more to create and test our web applications effectively.
- It gives CLI (Command Line Interface) tool to create and test Spring Boot (Java or Groovy) Applications from commanding prompt very easily and rapidly.
- It gives lots of modules to create and test Spring Boot Applications effectively utilizing Build Tools like Maven and Gradle
- It provides loads of plug-ins to work with implanted and in-memory Databases effortlessly.
What do Dev Tools in Spring boot mean?
View answer
Spring boot accompanies Dev Tools, which is acquainted with increase the profitability of designer. You don’t have to redeploy your application each time you influence the changes. The developer can reload the progressions without restart of the server. It maintains a strategic distance from the agony of redeploying application each time when you roll out any improvement. This module will can’t be utilized in a production environment.
What does Spring Boot Starter Pom mean? Why Is It Useful?
View answer
Starters are an arrangement of advantageous reliance descriptors that you can incorporate into your application. The starters contain a considerable amount of the dependencies that you have to get a task up and running rapidly and with a steady, supported a set of managed transitive conditions.
The starter POMs are helpful reliance descriptors that can be added to your application’s Maven. In another word, if you are building up a project that utilizes Spring Batch for batch preparing, you need to incorporate spring-boot-starter-bunch that will import all the required conditions for the Spring Batch application. This decreases the burden of looking at and designing all of the conditions required for a structure.
Why do we use “Opinionated” in spring boot?
View answer
It takes after "Opinionated Defaults Configuration" Approach to lessen Developer exertion. Because of the Opinionated perspective of spring boot, what is required to begin yet additionally we can get out if not appropriate for the application. Spring Boot utilizes sensible defaults, “opinions,” for the most part in light of the classpath substance.
What are esteem properties of Spring Boot?
View answer
Spring Boot gives different properties, which can be indicated in our project’s application. Properties record. These properties have default values, and you can set that inside the properties record. Properties are utilized to set qualities like a server-port number, database association configuration and much more.
How Might You Implement Spring Security In Spring Boot Application?
View answer
Usage of spring security in Spring boot application requires quite a little configuration. You have to include spring-boot-starter-security starter in pom.xml. You need to make spring config class, which will expand WebSecurity Configure Adapter and override expected strategy to accomplish security in Spring boot application.
Differentiate Between An Embedded Container And A War?
View answer
There is no force to go containerless:
- The embedded container is only one component of Spring Boot
- Traditional WAR additionally benefits a considerable measure from Spring Boot
- Automatic Spring MVC setup, including Dispatcher Servlet
- Sensible defaults in light of the class-path content
- The embedded container can be utilized during improvement.
Explain the difference between JPA and Hibernate?
View answer
JPA is a specification/Interface whereas Hibernate is one of the JPA implementations.
What does Aspect-Oriented Programming (AOP) mean?
View answer
Aspect Oriented Programming (AOP) supplements Object-Oriented Programming (OOP) by giving another mindset about program structure. The key unit of measured quality in OOP is the class, while in AOP the unit of particularity is the viewpoint. Angles empower the modularization of concerns, for example, transaction management that cut over numerous sorts and questions.
What is the difference between RequestMapping and GetMapping in Spring Boot?
View answer
Both @GetMapping and @RequestMapping are annotations for mapping HTTP GET requests onto specific handler methods in Spring boot. @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping. @GetMapping is the newer annotation.
What is JavaConfig?
View answer
Spring JavaConfig is a product of the Spring community that provides a pure-Java approach to configuring the Spring IoC Container. It thus helps avoid using XML configurations. The advantages of using JavaConfig are:
Object-oriented configuration. Because configurations are defined as classes in JavaConfig, users can take full advantage of object-oriented features in Java. One configuration class may subclass another, overriding its @Bean methods, etc.
Reduced or eliminated XML configuration. The benefits of externalized configuration based on the principles of dependency injection have been proven. However, many developers would prefer not to switch back and forth between XML and Java. JavaConfig provides developers with a pure-Java approach to configuring the Spring container that is conceptually similar to XML configuration. It is technically possible to configure the container using only JavaConfig configuration classes, however in practice many have found it ideal to mix-and-match JavaConfig with XML.
Type-safe and refactoring-friendly. JavaConfig provides a type-safe approach to configuring the Spring container. Thanks to Java 5.0's support for generics, it is now possible to retrieve beans by type rather than by name, free of any casting or string-based lookups.
How to implement JWT authentication for Spring Boot Application?
View answer
JWT stands for JSON Web Token. JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. The client will need to authenticate with the server using the credentials only once. During this time the server validates the credentials and returns the client a JSON Web Token(JWT). For all future requests the client can authenticate itself to the server using this JSON Web Token(JWT) and so does not need to send the credentials like username and password.
How to disable Actuator endpoint security in Spring Boot?
View answer
By default all sensitive HTTP endpoints are secured such that only users that have an ACTUATOR role may access them. Security is enforced using the standard HttpServletRequest.isUserInRole method. We can disable security using: management.security.enabled=false
It is suggested to disable security only if the actuator endpoints are accessed behind firewall.
Have you integrated Spring Boot and ActiveMQ?
View answer
For integrating Spring Boot and ActiveMQ we use the spring-boot-starter-activemq dependency. It requires very little configuration and no boilerplate code.
How to implement Pagination and Sorting with Spring Boot?
View answer
Using Spring Boot achieving pagination is very simple. Using the Spring Data-JPA this is achieved passing pageable org.springframework.data.domain.Pageable to the repository methods.
What is Swagger? Have you implemented it using Spring Boot?
View answer
Swagger is widely used for visualizing APIs, and with Swagger UI it provides online sandbox for frontend developers. For the tutorial, we will use the Springfox implementation of the Swagger 2 specification. Swagger is a tool, a specification and a complete framework implementation for producing the visual representation of RESTful Web Services. It enables documentation to be updated at the same pace as the server. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Thus Swagger removes the guesswork in calling the service.
What is Spring Batch? How do you implement it using Spring Boot?
View answer
Spring Boot Batch provides reusable functions that are essential in processing large volumes of records, including logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management. It also provides more advanced technical services and features that will enable extremely high-volume and high performance batch jobs though optimization and partitioning techniques.Simple as well as complex, high-volume batch jobs can leverage the framework in a highly scalable manner to process significant volumes of information.
What is FreeMarker Template? How do you implement it using Spring Boot?
View answer
FreeMarker is a Java-based Template Engine, originally focusing on dynamic web page generation with MVC software architecture. The major advantage of using Freemarker is the complete separation of the Presentation layer and the Business Layer. The Programmers can work on the application code while the designers can work on the html page design. Finally using freemarker these can then be combined to give the final output page.
What is caching? Have you used any caching framework with Spring Boot?
View answer
A cache is an area of local memory that holds a copy of frequently accessed data that is otherwise expensive to get or compute. Have used Hazelcast for caching.
What is CSRF attack? How to enable CSRF protection against it?
View answer
CSRF stands for Cross-Site Request Forgery. It is an attack that forces an end user to execute unwanted actions on a web application in which they are currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request.
When will you use WebSockets? How tto implement it using Spring Boot?
View answer
WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection.
- WebSocket are bi-directional - Using WebSocket either client or server can initiate sending a message.
- WebSocket are Full Duplex - The client and server communication is independent of each other.
- Single TCP connection - The initial connection is using HTTP, then this connection gets upgraded to a socket based connection. This single connection is then used for all the future communication
- Light - The WebSocket message data exchange is much lighter compared to http.
What is AOP? How to use it with Spring Boot?
View answer
During software development, functions that span multiple points of an application are called cross-cutting concerns. These cross-cutting concerns differ from the application’s main business logic. Hence ,separating these cross-cutting concerns from the business logic is where aspect-oriented programming (AOP) comes into picture.
How can we monitor all the Spring Boot Microservices?
View answer
Spring Boot provides actuator endpoints to monitor metrics of individual microservices. These endpoints are very helpful for getting information about applications like if they are up, if their components like database etc are working good. But a major drawback or difficulty about using actuator enpoints is that we have to individually hit the enpoints for applications to know their status or health. Imagine microservices involving 50 applications, the admin will have to hit the actuator endpoints of all 50 applications.
Explain thymeleaf in Spring Boot.
View answer
Thymelaf is a server-side Java template engine for a web application. It helps you to bring elegant natural templates to your web application.
Can you disable the default web server in the Spring Boot application?
View answer
Yes, we can disable the default web server by using application.properties to configure the web application type.
What is Swagger2?
View answer
Swagger is used to describing the structure of APIs. Swagger 2 is an open-source service provided in Spring Boot which makes it easier for the machines to find out the structure of APIs like RESTful Web services.
What are the major benefits of spring Externalized Configuration?
View answer
Externalized Configuration helps to work with the same code in different environments. Developers can use YAML files, properties files, command-line arguments, and environment variables to externalize configuration.
Define ELK stack.
View answer
The ELK Stack is made of three open-source products: 1) Elasticsearch, 2) Logstash, and 3) Kibana.
- Elasticsearch: It is a NoSQL database which is based on the open-source search engine called Lucene.
- Logstash: It is a data processing pipeline tool which accepts inputs from sources, performs different transformations, and exports the data to targets.
- Kibana: Kibana helps users to visualize data with graphs and chart in Elasticsearch.
Explain CORS in Spring Boot?
View answer
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.
Explain different types of dependency injection.
View answer
There are two types of dependency injection in Spring Boot. They are as follows:
- Constructor based dependency injection: It is a technique in which one class object supplies the dependency of another object.
- Setter-based dependency injection: It is a dependency injection in which the framework injects the primitive and string-based values using setter method.
What are the advantages of micro services?
View answer
Following are the major advantages of micro services:
- It makes development fast and easy.
- Compatible with all container.
- Reduce production time.
- It's a lightweight model that supports a major business application.
What is join point in Spring Boot?
View answer
It is a program execution point like the handling of an exception or the execution of a method. In AOP, a join point is referred to as a method execution.
List out benefits of using the JavaConfig method.
View answer
Following are the benefits of JavaConfig method.
- User can take benefit of object-oriented configuration.
- Spring Boot configuration improves the efficiency of web-based application by eliminating complex XML configuration.
What are disadvantages of Spring boot?
View answer
If you want to convert your old spring application to Spring boot application, it may not be straight forward and can be time consuming.