50 Frequently asked Springboot Interview Questions and Answers

For freshers and experienced people, we have compiled a collection of the most commonly asked and important Spring Boot Framework interview questions. This section teaches you how to comprehend spring boots and how to succeed in technical interviews.

1. Why Spring Boot Framework?

  • No XML based Congirations
  • Easy Logging Setup

2. What are the Main Components of Spring Boot?

  •   Starters POMs
  •   Actuators of Spring Boot
  •   SpringBoot CLI
  •   Spring Boot Auto Congirations

3. What are all the Pre-requisite for Springboot Development?

  • JDK (Latest version is preferable)
  • Maven Repository
  • Development Tool (Eg: Eclipse)
  • Servers (Tomcat / Jetty) 

Now you are good to go for SpringBoot Development 

4. Why We Choose SpringBoot over Spring?

We all know that Spring Boot is the advanced layer of the Spring Framework, But still, Spring Boot provides that Spring does not.

  • Starter POMs
  • No XML Configurations
  • Full automated Configuraions
  • Inbuilt Servers(Tomcat, Jetty)
  • Component Scanning
  • Actuators
  • InMemory DB

It Simplifies the features and makes it easy to reach the user.

5. What is the Spring Boot Flow Architecture?

  • Model
  • View
  • Controller
  • Database
spring boot architecture flow diagram

6. Usage of @Configuration Annotation in Spring Boot?

@Configuration IS PART OF Spring Code Framework. It is mainly to identify the bean methods of a Class which is pointed with @Configuration annotation. When we define the Class as Configuration, the Spring Framework loads the into Spring Container and finds and loads the bean methods of the class into Spring Beans.

7. What are Starter Dependencies in Springboot?

Starter Dependencies is nothing but a Dependency section in Maven. So in this section, we define the necessary dependencies in the form of artifactId. Spring Boot application knows the types of application only by these starter dependencies sections.

Eg :

<dependency>
<groupId> org.springframework.boot</groupId>
<artifactId> spring-boot-starter-web </artifactId>
</dependency>

8. Varieties of Starter dependencies in SpringBoot?

There are plenties of dependencies available for Spring Boot Framework, below are the most commonly used starter dependencies.

  •  <spring-boot-starter-data-jpa> – To Implement Data JPA starter.
  •  <spring-boot-starter-test> – To Implement Test starter.
  •  <spring-boot-starter-security> – To Implement Security starter.
  •  <spring-boot-starter-web> – To Implement Web starter.
  •  <spring-boot-starter-mail> – To Implement Mail starter.

 Eg :

 

<dependency>  
<groupId>org.springframework.boot</groupId>  
<artifactId>spring-boot-starter-data-jpa</artifactId>  
<version>2.2.2.RELEASE</version>  
</dependency>  

The above code refers to the Starter dependencies for Data JPA

9. What is SpringApplication.run in Springboot?

The classes which considered as Main Class defined by the annotation @SpringBootApplication. This main class invokes the SpringApplication.run method to bootstrap the application and the necessary parameter will get loaded into the spring container.

@SpringBootApplication 
public class MySpringBootApplication { 
    public static void main(String[] args) {    
        SpringApplication.run(MyApplication.class);        
    } 
}

10. What is Spring Initializer?

Spring Initializer is nothing but a simple web application that helps the users to set up the spring basic requirements such as supporting document files (maven files or Gradle files) and make the project structures. So it is really helpful for the freshers to have an idea of what the spring boot basic structure looks like. 

11. What is Spring Boot CLI?

CLI is a Comand Line Interface that allows you to create a spring-based application by Groovy. The handling of this will be much easier than you think. If you want to use JDBC Environment, all you need to do is select the JDBC template, It will take care of other necessary tasks of the templates.

12. What are the basic Spring Boot CLI commands?

  • -run
  • -test
  • -grap
  • -jar
  • -war
  • -install
  • -uninstall 
  • –init
  • -shell
  • -help

13. Basic Annotations of Spring Boot?

Below are the most commonly used basic annotations in Spring Boot.

  • @SpringBootApplication
  • @Configuration
  • @ComponentScan
  • @Bean
  • @EnableAutoConfiguration

14. Usage of @RestController annotation in Springboot?

@RestController is used for implementing restful services in Springboot. Whenever the HTTP request is received the Controller will look for the classes annotated with @RestController to find the relevant mapping for the incoming requests. 

15. What are all the most common annotations used with @RestController in Spring Boot?

  • @PostMapping
  • @GetMapping
  • @RequestHeader
  • @RequestBody

16. What is Spring Eureka and what are the usages of this?

Spring Eureka is nothing but an application, it holds the detailed information of Client-Server applications. Spring Eureka is known to hold every application’s port and IP details of running instances. These port and mapping details will be used for all the microservices registered on the Spring Eureka. 

Simply we can mention, it is connecting server between the applications.

17. What is the difference between @ResponseBody and @RequestBody annotation?

@RequestBody :

To map the values from the Original HTTP Request Body straight into your java model classes. Before you map, you have to ensure the relevant model has been created to receive the request straight into the classes

@ResponseBody :

To generate and send the HTTP responses with the method provided. Both @RequestBody and @ResponsBody are used against specific methods in a controller.

Example :

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public HttpStatus addItem(@RequestBody Item item) 
{
    return HttpStatus.OK;
}

18. What are all the basic annotations used in Spring RestFul Services?

  • @RestController
  • @Controler
  • @RequestBody
  • @ResponseBody
  • @PostMapping
  • @RequestHeader

19. Uses of @ControllerAdvice annotation in SpringBoot?

@ControllerAdvice: ControllerAdvice is used in the Exception Handling part in Spring Boot, It is an Informer to Spring Controller saying that it has the ExceptionHandler methods so that the methods can be scanned and used across the application to handle the exception properly. 

In the default mechanism, @ControllerAdvice will be applied in all the classes, those are marked with @controller annotation

20. What is the use of @@ExceptionHandler in SpringBoot?

ExceptionHandler is used to annotate the method. It is a Global Exception Handler, captures the Exceptions and translates it as HTTP responses. It also represents what types of Exceptions are to be handled. it has arguments through which it accepts the exception instances and the request

21. What is the use of @RequestMapping?

@RequestMapping annotation is defined within the @Controller classes, The process of Routing the HTTP request to a destination method is achieved by making the method with @RequestMapping.

Example :

@Controller
@RequestMapping("/admin")
public class AdminController {

	@RequestMapping("/data")
	public String getData() {
		
	}
}

@GetMapping or @PostMapping @PutMapping can be achived by RequestMapping annotation as follows,

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getItems()

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity getItems()

22. What is Microservices ?

Microservices are an Independent architecture and it’s a standalone application. 

An enterprise application is divided intp multiple scalable small applications, each of these small application can work indepently without depending on other small applications. This term is called as Micro services.

23. What is the advantages of using Microservices?

  • Easy to maintain and testable
  • Loosely Coupled between other applications.
  • Standalone architecture and design.
  • Easy to deploy independently.

24. What is the difference between REST API and Micro Services ?

Before knowing the differences, We must know the similarities between these. Aim of these two services are to achieve Standalone Independent Architecture.

Micro Services :

  • Micro Services are Standalone Independent Applications with an Architecture.
  • Scalable, Works Independently

REST API :

  • REST API is a simple small-sized service, It is not an application, REST will help the application to make Standalone Environment. 
  • Scalable, Work Independently.

25. Define Spring Cloud :

It is a Short-lived framework used to Create the application quickly. It contributes significantly to microservice due to its quick association with cloud services

  • Distributed Configuration
  • Distributed Messaging
  • Routing 
  • Cluster State
  • Service to Service Calls
  • Load Balancing
  • Circuit Breakers
  • Global Locks 
  • Service Discovery
  • Service Registration

26. What is an actuator in Spring Boot?

The actuator is a kind of project. It provides restful services to know the current state of the application. that means actuator monitor

  • state of the application
  • Performance of the application
  • It also manages the usage of the entire application.

These things are done by actuators without having any additional codes for application.

27. What are all the advantages of SpringCloud over Distributed Systems?

  • Common Issues by Distributed Systems  – Network, latency, bandwidth, security issues
  • Service Discovery: Locate and Communicate the Resources within the cluster 
  • Load Balancing: Optimize the workload among resources
  • Performance Optimization: Reduce the plenty of Performance issues caused by a variety of operational loads.

28. What are all the Spring Boot Starters?

Most Commonly used starter Maven dependencies

  • spring-boot-starter – Spring Auto Configuration Support
  • spring-boot-starter-aop – AOP, Logging, YAML Support
  • spring-boot-starter-data-jpa – Spring DATA, JPA and Hibernate Support
  • spring-boot-starter-security – Spring Security Support
  • spring-boot-starter-test – Spring Test Applications
  • spring-boot-starter-web – Web Application Dependencies such as RestFUL Support

29. What application Properties do in Spring Boot?

application Properties available under resources folder, the application.properties file used to Configure

  • Customized Configuration for the entire application
  • Configuration for server related configuration

application properties is coupled with Spring Boot Framework with many default properties to control / override the existing configuratio of the application.

30. What do YAML Properties do in Spring Boot?

YAML comes from Snake YAML jar from spring-boot-starter-aop dependencies.

31. What is the Difference between YAML and Application properties?

YAML :

  • Hierarchy based configurations
  • Support Multiple Profiles in the same file, differentiated with “—“
  • Should be placed in a Classpath folder
  • List Structure Allowed
  • Accessed over @Value, Environment API

Properties :

  • Row-based configurations
  • Support Multiple Profiles as different files.
  • Should be placed in a Classpath folder
  • List structure allowed
  • Accessed over @Value, Environment API

32. @Value Annotation in Spring Boot?

@Value annotation is used to read the property details from application properties.

Syntax :

@value("${property_key}")

Example :

@Value("${spring.application.name}")
private String name;

Here name field holds the property value of spring.application.name

33. @Autowired in Spring Boot ?

Load the classes automatically into the context is called Autowired. This can be achived by the annotation @Autowired.

If we want to Inject a class, the class should be loaded into spring boot application context. Then only we can inject that class into our destination classes. 

To load this class into application contect we must use the scanning annotaions which will scan the classes into the context.

There will be two techiniques in scanning annotations

@Configuration @ComponentScan("com.example.sample")

This will load the class into applicatio context, But this need to defined in all the classes whichever to be loaded into the context. 

So in Spring Boot V2, we have an option to scan namely

@SpringBootApplication 

This annotation will scan entire application (classes of sub packages ) and loads into the context. So if we define this annotation in main class. Entire classes will be loaded into the application context and it can be injected whenever neeeded.

34. @Component annotation in Spring Boot ?

@Component is a Class Level annotation in spring boot.

It is used to mark the class as Component So that the annotated will be detected by the Spring Container and loads the class into Application Context as a Bean.

35. @Controller Annotaion in Spring Boot ?

It is similar to @Component annotaion, It is a class level annotaion. @Controller annotaion informs the Spring Framework that the class is a HTTP Handler. 

Generally, this annotation is used to work with mapping annotations for Web Request.

36. @Service annotation in Spring Boot?

These annotations inform the SpringBoot like the class is capable of doing service implementations such as operations, calculations, call external services, etc.

When we define the Class as @Service the Spring Context consider the class as part of the Service layer and load it into the classpath.

This is class-level annotation in Springboot.

37. @EnableAutoConfiguration in Spring Boot?

This annotation is mainly used in Main Class to enable the automatic configurations for Spring Boot. Configurations such as Properties, Beans Loading, Classpath enabling.

@EnableAutoConfiguration is depreciated from Spring Boot 1.2.0 version because @SpringBootApplication annotation does this job.

38. @SpringBootApplication Annotation in Spring Boot ?

This annotation is the heart of all other annotation this will be defined in Main Class. This annotaion do the configurations and scanning components of Current and Sub packages classes.

@SpringBootApplication annotation overrides @EnableAutoConfigurations, @ComponentScan, @Configuration from Spring Boot Version 1.2.0.

39.  @GetMapping vs @PostMapping vs @DeleteMapping vs @PutMapping vs @PatchMapping in Spring Boot?

@GetMapping :

This annotaion used to map the HTTP GET Request into the destination @GetMapping annotated method.

Example :

@GetMapping
public ResponseEntity<Items> getItems() 

@PostMapping :

This annotaion used to map the HTTP POST Requestion in to the destination method.

Example :

@PostMapping
public ResponseEntity<Items> getItems() 

The same logics for @PutMapping, @DeleteMapping, @PatchMapping

40. @PathVariable Annotaion in Spring Boot ?

This annotation used to extract the values from URI in Rest Services, This annotation take the values from the URI and convert into the object type mentioned in the method.

This annotaion is a method level annotaion used to work with REST Services.

41. @RequestParam annotation in Spring Boot?

Its a Query Parameter in Spring Boot, This annotaion is used to extract the query parameter from the URL. 

@RequestParam used to fetch the data from the URL, pointed with queries

Example :

@GetMapping("/home")
@ResponseBody
public String getHomeIdQueryParam(@RequestParam String id) { return "ID: " + id; }

http://localhost:8080/springboot/home?id=xyz 

Result : xyz

Also note that Query Param is decoding while retrieving the param values

http://localhost:8080/springboot/home?id=xy+z 

Result : xy z

42. @RequestHeader annotation in Spring Boot ?

It used to receive the HTTP Request Headers of an Rest Request. It is a method level parameter.

Using this annotaion we are able to capture the Header values seperately or in whole map.

Some of the optional elements are  name, value, required, defaultValue.

Example :

@GetMapping("/home/data")
public ResponseEntity<String> listData( @RequestHeader Map<String, String> headers) 
{
headers.forEach((key, value) -> { Logging.info(String.format("Header '%s' = %s", key, value)); 
});
return HttpStatus.OK; 
}
@GetMapping("/home/data") 
public ResponseEntity<String> listData( @RequestHeader("my-number") int number) {
 Logging.info(number); 
return HttpStatus.OK; 
}

43. @RestController annotaion in Spring Boot ?

@RestController is used to define the Class as Rest Based, When we define the class as @RestController the Spring Boot Context consider the Class as Rest Based and whenever the HTTP Request Received the Controller look for the classes annotated with @RestController.

@RestController annotation overrides the annotations such as @Controller and @ResponseBody.

44. @RequestAttribute Annotation in Spring Boot ?

This annotation is used to bind the value to the Request Parameters 

It is a method level annotation works with RequestMapping

Example :

@RequestMapping("/home")
public String setCounter(@RequestAttribute("counter") Counter counter) {
counter.setCount(counter.getCount() + 1);
return counter.toString();
}

So whenever the request raised, the count is assigned through this method. Binding the value into the request.

45. @CookieValue annotation in Spring Boot ?

It is a method level annotaion works with @RequestMapping. This is used to get cookie value avalable in the HTTP Cookie.

value, defaultValue, required are optional attributes of @CookieValue annotaion.

Example :

  @RequestMapping
    public String itemRequest (
                        @CookieValue(value = "myCookieName",
                                            defaultValue = "defaultCookieValue", required = false)
                        String cookieValue, Item item) {
        System.out.println(cookieValue);
.......
        return "result";
}

46. @CrossOrigin annotation in Spring Boot ?

This annotaion used in Class and method level. It enables cross-domain communication

47. @ComponentScan Annotations in Spring Boot ?

This annotation is used to scan the packages and look for the Beans and load the beans into application context. So the beans can used anywhere it required as Injection.

It is usually works with the annotation @Configuration.

@ComponentScan was overrided by @SpringBootApplication annotaion since the version 1.2.0

48. @Qualifier annotaion in Spring Boot ?

This annotaion usuaally works with @AutoWired annotaion, the main puporpose of having this annotaion is used to avoid the conflict of the same impletations by different components.

For example, Class A, Class B implements Interface C, Now if we try to Inject Interface C in Class D, System will throw an Error NoUniqueBeanDefFoun, This is because mulple classes tries to implement the Interface C, So Springdoes not know which oneto inject.

To overcome this If we mention the @Qualifier Annotaion in Class D, Spring Consider the neccessary and inject the Interface properly. 

Example :

@AutoWired
 @Qualifier("classA") 

49. @Lazy Annotation in Spring Boot?

This annotation makes the Spring Boot to become lazy on Component Scanning. That means on Startup the Spring Context scan all the Classes @Autowired and load it to memory for Injection. This annotaion informs the Spring not to scan and load on initial startup. Instead it tells the Spring to AutoWire when request is initiated.

it is a Class level annotation.

Example :

@Lazy
@Configuration
@ComponentScan(basePackages = "com.example")
public class HomeConfig {
//Codes
}

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *