Spring Boot Interview Questions
Published on

Spring Boot Interview Questions

Authors

In this post, I am talking about the most common questions that the interviewer can ask on Spring Boot, in case you didn't know what Spring Boot is, Its a Java Library most commonly used for building web applications, Spring Boot is a vast library, Which you can learn more about in it from the official website.

Please go thoroughly read the below post so that you don't miss out on any basic questions on Spring Boot.

Table of Contents

Which version of Spring supports the Java 11 LTS version?

Spring 5.3 and above support Java 11. Similarly Spring 2.1.x and above had started to supporting it.

What is a bean?

A bean is an object that is instantiated, assembled, and otherwise managed by a Spring.

As per the example below, we can see that we don’t have to worry about instantiating BeanA before calling BeanB, all of this is taken care of by Spring itself.

import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
import org.springframework.boot.CommandLineRunner;
@SpringBootApplication
public class Application {
	public static void main(String[] args) {
		ApplicationContext ctx = SpringApplication.run(Application.class, args);
	}

	@Bean("A")
	public CommandLineRunner BeanA(ApplicationContext ctx) {
		return args -> {
			System.out.println("Hello from A Bean");
		};
	}

	@Bean("B")
	@DependsOn("A")
	public CommandLineRunner BeanB()
	{
		return args -> System.out.println("Hello from B Bean");
	}
}

What is the latest version of spring?

Latest version of spring boot is 2.4.5 so if you’re using 2.4.X and above then it’s a very recent version of spring boot.

You can see that the initial Spring release was ~17 years ago, major framework versions being released every 3-4 year.

Difference between Spring Framework, Spring Boot and Spring MVC?

Spring Framework

Spring Framework is the most popular application development framework of Java.

The main feature of the Spring Framework is dependency Injection or Inversion of Control (IoC).

Spring MVC

Spring Model View Controller, which is a complete HTTP oriented MVC framework managed by the Spring Framework and based in Servlets.

Spring Boot

Spring Boot is a module of Spring Framework. It allows us to build a stand-alone application with minimal or zero configurations. It is better to use if we want to develop a simple Spring-based application or RESTful services.

It’s a whole package which focuses on rapid development, Spring Web packages includes Spring MVC.

What are the benefits of using Spring?

  • Lightweight − Spring is lightweight when it comes to size and transparency. The basic version of the spring framework is around 2MB.
  • Inversion of control (IOC) − Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
  • Aspect-oriented (AOP) − Spring supports Aspect-oriented programming and enables cohesive development by separating application business logic from system services.
  • Container − Spring contains and manages the life cycle and configuration of application objects.
  • MVC Framework − Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks such as Struts or other over-engineered or less popular web frameworks.
  • Transaction Management − Spring provides a consistent transaction management interface that can scale down to a local transaction (using a single database, for example) and scale up to global transactions (using JTA, for example).
  • Exception Handling − Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO, for example) into consistent, unchecked exceptions.

What are the types of IoC containers? Explain them.

There are two types of IoC containers −

Bean Factory container − This is the simplest container providing basic support for Dependency Injection. The BeanFactory is usually preferred where the resources are limited, like mobile devices.

Spring ApplicationContext Container − This container adds more enterprise-specific functionality, such as resolving textual messages from a properties file and the ability to publish application events to interested event listeners.

Explain about Scope of Bean?

Bean ScopeDescription
singleton (default)Single bean object instance per spring container
prototypeOpposite to singleton, it produces a new instance every time a bean is requested.
request

A single instance will be created and available during the complete lifecycle of an HTTP request.

session

A single instance will be created and available during the complete lifecycle of an HTTP Session.

application

A single instance will be created and available during the complete lifecycle of ServletContext.

websocket

A single instance will be created and available during the complete lifecycle of WebSocket.

@Component
@Scope("application")
public class BeanClass {
}

Difference between a prototype and request scope in spring boot?

Prototype creates a brand new instance every time you call getBean on the ApplicationContext. Whereas for Request, only one instance is created for an HttpRequest.

Let’s take an example of HttpRequest, I can call getBean twice on Application, and there will only ever be one bean instantiated. In contrast, that same bean scoped to Prototype in that same single HttpRequest would get 2 different instances.

HttpRequest scope

CodingJump bean1 = context.getBean("codingjump");
CodingJump bean2 = context.getBean("codingjump");
bean1 == bean2; //This will be true

Prototype scope

CodingJump bean1 = context.getBean("codingjump");
CodingJump bean2 = context.getBean("codingjump");
bean1 == bean2; //This will be false

What is the difference between ServletContext and ApplicationContext in Spring Boot?

ServletContext

Every Java web application based on Servlet technology will have a servlet context, whether it’s a spring application or not.

There’s only one ServletContext for an entire web app, and all the parts of the web app share it.

ApplicationContext

Every Spring webapp has an associated application context that is tied to its lifecycle. It’s a container to hold Spring beans.

Use ApplicationContext if you want to retrieve the information of Spring beans; use ServletContext if you want to get/set attributes shared to all Servlets.

What is a WebSocket in Java?

WebSockets is a bi-directional, full-duplex, persistent connection between a web browser and a server. Once a WebSocket connection is established the connection stays open until the client or server decides to close this connection.

How long can a websocket connection last?

A WebSocket connection can in theory last forever. Assuming the endpoints remain up, one common reason why long-lived TCP connections eventually terminate is inactivity also TCP connections on most networks eventually get terminated by some outage or other.

Difference between @Component and @Bean in Spring Boot?

@Component

  1. Component is a class level annotation.
  2. @Controller, @Repository, @Service are all specializations of @Component
  3. Component class needs to be auto-scanned by Spring for registering those beans of the component class.

@Bean

  1. Bean is a method-level annotation, and the name of the method serves as the bean default name; you can also give custom names if needed.
  2. We can control instance creation logic with a scope like a singleton, prototype, request, etc.
  3. @Configuration or @Component needed for using @Bean

What is @SpringBootApplication Annotation?

Single @SpringBootApplication is collection of the three annotations:

  • @EnableAutoConfiguration: Enable Spring Boot’s auto-configuration mechanism
  • @ComponentScan: Enable @Component scan on the package where the application is located
  • @Configuration: Allow to register extra beans in the context or import additional configuration classes
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

Why Is @Primary Needed?

In some cases, we need to register more than one bean of the same type.

In this example we have RahulEmployee() and SuryaEmployee() beans of the Employee type:

@Configuration
public class Config {
    @Bean
    public Employee RahulEmployee() {
        return new Employee("Rahul");
    }
    @Bean
    public Employee SuryaEmployee() {
        return new Employee("Surya");
    }
}

Spring throws NoUniqueBeanDefinitionException if we try to run the application like below.

Employee employee = context.getBean(Employee.class);
System.out.println(employee);

Because there is more than one Bean which is of type Employee.class

To resolve this @Primary is introduced which will let Spring know which one to use if there is a clash.

Explain the @InitBinder in Spring Boot?

Initbinder comes into picture if you want to customize the request being sent to the controller.It is defined in the controller, helps in controlling and formatting each and every request parameter that comes to it.

It uses WebDataBinder to register a preprocessor, for example we might want to trim spaces before sending it to the controller.

In the example below I’ve used a PropertyEditor which will remove the first character from the name.

import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.*;
import java.beans.PropertyEditorSupport;
// skips the first character from the name
class NameEditor extends PropertyEditorSupport {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        text = text == null ? text : text.substring(1);
        setValue(text);
    }
}
@RestController
public class HelloController {
	// Both name and test parameters
	@InitBinder
	public void initBinder(WebDataBinder dataBinder) {
		System.out.println("Runs for every parameter");
	}
	// only applicable for name parameter
	@InitBinder({"name"})
	public void initBinder2(WebDataBinder dataBinder) {
		System.out.println("Runs only for name parameter");
		dataBinder.registerCustomEditor(String.class, new NameEditor()); // Registering NameEditor for String
	}
	@RequestMapping("/test")
	public String test(String name, String address)
	{
		return name + ";" + address;
	}
}

What is a ViewResolver in Spring boot?

The ViewResolver maps view names to actual views. Spring framework comes with quite a few view resolvers e.g. InternalResourceViewResolver, XmlViewResolver, ResourceBundleViewResolver and a few others.

Say the user is typing in “home”, then the prefix is “/WEB-INF/views/” and the suffix is “.jsp” then “home” will be resolved to “/WEB-INF/home.jsp” by InternalResourceViewResolver.

Explain about WebDataBinder?

Special DataBinder for data binding from web request parameters to JavaBean objects. Designed for web environments.

What is DevTools in Spring Boot?

Spring Boot DevTools helps you to increase the productivity of the developer. So, you aren’t required to redeploy your application every time you make the changes. It allows the developer to reload changes without the need to restart the server.

What is a Spring Boot Actuator?

Spring Boot Actuator allows you to monitor and manage your application when you want to push it for the production. It helps you to control your application by using HTTP endpoints.

There are three main features of Spring Boot Actuator:

  1. Endpoints
  2. Metrics
  3. Audit

List the possible sources of external configuration?

  • Application Properties – By default, Spring Boot searches for the application properties file or its YAML file in the current directory, classpath root, or the 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 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.

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.

What are the Spring Boot starters and what are available the 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. A 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

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 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-devtools</artifactId>
</dependency>

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

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.

@Component
@ConfigurationProperties("coder")
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:

coder.number: 1
coder.value: false
coder.message: CodingJump

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

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

Explain about profiles in Spring Boot?

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

What is @RestController annotation in Spring Boot?

The @RestController is a stereotype annotation. It adds @Controller and @ResponseBody annotations to the class. We need to import org.springframework.web.bind. annotation package in our file to implement it.

What is RAD model?

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

RAD model has the following phases:

  • Business Modeling
  • Data Modeling
  • Process Modeling
  • Application Generation
  • Testing and Turnover

What is Cross-Site Request Forgery attack?

A cross-Site Request Forgery attack or one-click attack is an attack that forces other users to execute malicious commands on the application. CSRF attack specifically targets state-changing requests.

What is mean by spring batch?

Spring Boot Batch provides code reusability, which is important when working with large numbers of records, including transaction management, logging, skipping, job processing statistics, and job restarts.

Explain CORS in Spring Boot?

CORS stands for Cross-Origin Resource Sharing, is a mechanism implemented by browsers and helps users authorize cross-domain requests. This mechanism serves as an alternative to less secure and less powerful hacks of IFrame or JSONP.

Explain the difference between an embedded container and a WAR.

The main difference between these two is:

Embedded containers help you run the Spring Boot application as a JAR from the command prompt without setting up any web server, while to run a WAR, you need first to set up Tomcat.

What are the advantages of micro service?

  • It makes development fast and easy.
  • Compatible with all containers.
  • Reduce production time.
  • It’s a lightweight model that supports a major business application.

Why is @Service annotation used in spring boot?

Spring @Service annotation is used with classes that provide some business functionalities. Spring context will autodetect these classes when annotation-based configuration and classpath scanning is used.

Why is @Repository annotation used in spring boot?

Spring @Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.

What is Idempotent method?

An idempotent HTTP method is an HTTP method that can be called many times without different outcomes. It would not matter if the method is called only once, or ten times over. The result should be the same.

Idempotence essentially means that the result of a successfully performed request is independent of the number of times it is executed. For example, in arithmetic, adding zero to a number is an idempotent operation.

Can you give me an example of idempotent method in HTTP?

Idempotent REST APIs are GET, PUT, DELETE, HEAD, OPTIONS and TRACE HTTP methods. Only POST APIs will not be idempotent.

Generally PUT APIs are used to update the resource state. If you invoke a PUT API N times, the very first request will update the resource; then rest N-1 requests will just overwrite the same resource state again and again – effectively not changing anything. Hence, PUT is idempotent.

What do you mean Global Transaction in Spring Boot?

Quite often, we deal with operations that span across multiple resources. For instance, operation in two different databases or a database and a message queue. Here, local transaction support within resources will not be sufficient for us.

The XA Specification is one such specification which defines a transaction manager to control transaction across multiple resources. Java has quite mature support for distributed transactions conforming to the XA Specification through the components JTA and JTS.

What is JTA?

The Java™ Transaction API (JTA) allows applications to perform distributed transactions, that is, transactions that access and update data on two or more networked computer resources.

What is JTS in Spring?

JTS (Java Transaction Service) is a specification for implementing a Java transaction manager. A transaction manager serves as an intermediary between an application and one or more transaction-capable resource managers such as database servers and messaging systems. The JTS specification encompasses the JTA API specification.

How to implement Transaction in Spring Boot?

We will be using the @Transactional annotation. Transaction is a cross cutting concern and it is implemented using AOP in Spring Boot.

Spring Boot implicitly creates a proxy for the transaction annotated methods. So for such methods the proxy acts like a wrapper which takes care of creating a transaction at the beginning of the method call and committing the transaction after the method is executed.

What is the difference between http status codes 401 vs 403?

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. A server that receives valid credentials that are not adequate to gain access ought to respond with the 403 (Forbidden) status code.

What is a Micro Services architecture?

A microservices architecture breaks it down into a collection of smaller independent units. These units carry out every application process as a separate service. So all the services have their own logic and the database as well as perform the specific functions.

What is a Monolithic architecture?

The monolithic architecture is considered to be a traditional way of building applications. A monolithic application is built as a single and indivisible unit. Usually, such a solution comprises a client-side user interface, a server side-application, and a database. It is unified and all the functions are managed and served in one place.

Advantages & Disadvantages of Monolithic architecture?

Advantages

  • Less cross-cutting concerns. Cross-cutting concerns are the concerns that affect the whole application such as logging, handling, caching, and performance monitoring. In a monolithic application, this area of functionality concerns only one application so it is easier to handle it.
  • Easier debugging and testing. In contrast to the microservices architecture, monolithic applications are much easier to debug and test. Since a monolithic app is a single indivisible unit, you can run end-to-end testing much faster.
  • Simple to deploy. Another advantage associated with the simplicity of monolithic apps is easier deployment. When it comes to monolithic applications, you do not have to handle many deployments – just one file or directory.
  • Simple to develop. As long as the monolithic approach is a standard way of building applications, any engineering team has the right knowledge and capabilities to develop a monolithic application.

Disadvantages

  • Understanding. When a monolithic application scales up, it becomes too complicated to understand. Also, a complex system of code within one application is hard to manage.
  • Making changes. It is harder to implement changes in such a large and complex application with highly tight coupling. Any code change affects the whole system so it has to be thoroughly coordinated. This makes the overall development process much longer.
  • Scalability. You cannot scale components independently, only the whole application.
  • New technology barriers. It is extremely problematic to apply a new technology in a monolithic application because then the entire application has to be rewritten.

Advantages & Disadvantages of Micro architecture?

Advantages

  • Independent components. Firstly, all the services can be deployed and updated independently, which gives more flexibility. Secondly, a bug in one microservice has an impact only on a particular service and does not influence the entire application. Also, it is much easier to add new features to a microservice application than a monolithic one.
  • Easier understanding. Split up into smaller and simpler components, a microservice application is easier to understand and manage. You just concentrate on a specific service that is related to a business goal you have.
  • Better scalability. Another advantage of the microservices approach is that each element can be scaled independently. So the entire process is more cost and time-effective than with monoliths when the whole application has to be scaled even if there is no need in it. In addition, every monolith has limits in terms of scalability, so the more users you acquire, the more problems you have with your monolith. Therefore, many companies, end up rebuilding their monolithic architectures.
  • Flexibility in choosing the technology. The engineering teams are not limited by the technology chosen from the start. They are free to apply various technologies and frameworks for each microservice.
  • The higher level of agility. Any fault in a microservices application affects only a particular service and not the whole solution. So all the changes and experiments are implemented with lower risks and fewer errors.

Disadvantages

  • Extra complexity. Since a microservices architecture is a distributed system, you have to choose and set up the connections between all the modules and databases. Also, as long as such an application includes independent services, all of them have to be deployed independently.
  • System distribution. A microservices architecture is a complex system of multiple modules and databases so all the connections have to be handled carefully.
  • Cross-cutting concerns. When creating a microservices application, you will have to deal with a number of cross-cutting concerns. They include externalized configuration, logging, metrics, health checks, and others.
  • Testing. A multitude of independently deployable components makes testing a microservices-based solution much harder.

What is Spring Security?

Spring Security is a Spring project to support Authentication, Authorization and defense against common exploits, in a Spring based web application.

What is difference between Authentication & Authorization?

Authentication is the process wherein a system validates “Who are you”. Authentication is always precursor to Authorization.

Authorization is the process of validating “What resources can you access” in the application.

What is Principal?

A Principal represents a user’s identity.

What is AuthenticationEntryPoint?

What happens when a user tries to access a URL/ resource but hasn’t authenticated yet? We typically send the user back to some form to fill in the login details. Now, that is AuthenticationEntryPoint. It is entry point to access the application resources.

What is OAuth 2.0 ?

OAuth, also called Open Authorization, is an industry-standard protocol for Authorization.

It enables third-party applications get limited access on the user information. It does so with the help of four components also called OAuth roles:

  • Authorization Server
  • Resource Server
  • Resource Owner (User)
  • Client (Client application)

The OAuth2 protocol is all about how these different roles communicate with each other and completes the goal of limited access-control.