Spring Boot Interview Questions and Answers

Spring Boot Interview Questions and Answers

In case you’re searching for Spring Boot Interview Questions and Answers for Experienced or Freshers, you are at the correct place. GangBoard offers Advanced Spring Boot Interview Questions and answers that assist you in splitting your Spring Boot  interview and procure dream vocation as Spring Boot Developer.

Below are some of the most important Spring Boot Interview Questions and Answers frequently asked to tech aspirants. Our advanced list of Spring Boot Interview Questions contains all the necessary information for both freshers and experienced job seekers to crack an interview and begin an auspicious career as a Spring Boot Developer.

Q1) What is Spring Boot?

Answer: Earlier, while working with huge enterprise computing softwares, developers had to focus both on the coding part and on the mass amount of configurations. Consequently, this resulted in a problem where developers could not dedicate the needful amount of time to coding. Therefore, Spring Boot came into picture. Spring Boot is an architecture built on top of the conventional spring framework. It allows developers to create deployment ready applications with configurations and linked jar files.

Below are the 4 key Spring Boot components:

  • Spring Boot AutoConfigurator
  • Spring Boot Starters
  • Spring Boot Actuator
  • Spring Boot CLI

Q2) Why do we need Spring Boot?

Answer: This is one of the most frequently asked Spring Boot Interview Questions and Answers that you must be aware about. While Spring framework provides developers with an ideal environment to build large applications, it often involves a number of jar files, configurations, server establishment, dispatcher servlet, component scan, view resolver, and much more, which results as a hindrance to the development.

Spring Boot is designed to relieve developers from this rattling problem. It provides with features such as starter projects where developers can find pre built projects for further development, auto configurations, etc., so that the application developers can focus on the conventions.

Q3) How is Spring Boot architecture? Is it the same as Spring MVC?

Answer: Although Spring Boot is built as an architecture to Spring framework, it is not the same as Spring MVC, nor is a substitution to the latter one.

In simple words, Spring Boot is a mediator that helps a developer to connect, configure, and develop more easily and efficiently with the Spring framework.

Some of the auto configuration files provided by Spring Boot are database config, security config, and security config, which saves essential development time. Moreover, there are features such as Spring Boot Starters, which cannot to found in Spring MVC.

Q4) What is Spring Boot Starters?

Answer: Moving ahead with the Spring Boot Interview Questions and Answers, it is important to know about Spring Boot Starters, which is one of the 4 major components of Spring Boot. To build a single application, there are a lot of dependencies in the Spring framework. Spring Boot Starter POMs are designed to reduce these dependencies into a single one.

Therefore, instead of going through a lot of data to find a sample code and copy the dependencies, Spring Boot Starters provides developers with a ready to use all in one set of dependencies.

Some of the Spring Boot Starters are Web Starter, Test Starter, Mail Starter, Data JPA Starter.

Jar dependencies can be added to Maven’s pom.xml or Gradle’s build.gradle file.

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>

Q5) What is Spring Boot AutoConfiguration, and why do we need AutoConfiguration?

Answer: Spring Boot autoconfigurator is one of the 4 key components of Spring Boot. It uses defined jar dependencies to automatically add configurations to your Spring MVC application.

@Configurationpublic class MySQLAutoconfiguration {
}

Further, a class is registered under org.springframework.boot.autoconfigure.EnableAutoConfiguration key in the location resources/META-INF/spring.factories: This class acts as an auto configuration candidate.

org.springframework.boot.autoconfigure. EnableAutoConfiguration=\

com.training.springboot.autoconfiguration. MySQLAutoconfiguration

Q6) What is Spring Boot CLI?

Answer: CLI stands for the Command Line Interface. Spring Boot CLI, as the name suggests, is used to begin quickly with the development using the Spring framework. Often, developers have to spend a lot of time after writing boilerplate code, which is nothing but a few lines of code that has to be included time by time with a little bit of modification.

Groovy scripts provided by Spring Boot CLI makers sure that app developers can spend time after conventional coding parts and business logic. Such a set up makes sure Spring application is developed and deployed more quickly and efficiently.

Q7) What is Spring Boot Actuator?

Answer: Once the application is deployed, Spring Boot Actuator allows you to bring production-ready features to it. Features for monitoring application, traffic patterns, metrics, health, env, and other operation-related insights are provided by the Spring Boot Actuator. It makes use of HTTP endpoints to enable the interaction, which can be extended further in multiple ways same as other components of Spring Boot.

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

Note: Regardless of the Spring Boot version, the above setup remains true just as specified in the BOM(Spring Boot Bill of Materials).

Q8) How to create a Spring Boot Project?

Answer: While facing Spring Boot Interview Questions and Answers, a candidate might be asked to create a simple Spring Boot project, which can be easily accomplished following below guideline or one may create a Spring Boot project following the guidelines provided on https://start.spring.io/

Spring Boot Project

Folder Structure:

Folder Structure

The main method is the heart of the Spring boot application to run the application.

@SpringBootApplication:

The @SpringBootApplication annotation is the same as using @EnableAutoConfiguration, @Configuration, and @ComponentScan with default attributes.
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
}

Q9) What is @Configuration and why is it needed?

Answer: @Configuration is a Spring annotation that is used to indicate @Bean method declaration by a class. It can be processed by Spring container in order to create service requests and bean definitions during runtime.

@Configuration is:

Required, only when the annotated class is defined in the @ComponentScan annotation but is not passed explicitly.

Not Required, if the annotated class is passed in the source parameters while calling SpringApplication.run().

Q10) What is @RestController annotation?

Answer: @RestController is a specialized controller that includes @ResponseBody and @controller annotations. @RestController is mainly used to simplify the controller implementation.

@RestController
public class HelloController {
@RequestMapping(“/hello”)
public String greeting() {
return”HelloWorld”;
}
}

Q11) What is @RequestMapping annotation?

Answer: It is not unusual to be asked regarding various annotations while facing Spring Boot Interview Questions and Answers. However, do not hesitate and give your answer in simple terms using technical information such as below.

@RequestMapping is used to map class-level and method-level annotations.

  • It maps class-level annotations with the controller in the requested pattern or path.
  • Further, @RequestMapping specifies mappings to handler methods with method-level annotations.

Q12) What is @RequestBody annotation?

Answer: @RequestBody annotation is used to bind a method parameter to incoming HTTP requests with the mentioned URL in @RequestMapping annotation.

Here, HTTP message convertors are used to map HttpRequest body to a domain object, which consequently helps to automatically deserialize the body to a Java object based on header present in the request.

Q13) What is @ResponseBody annotation?

Answer: The task of @ResponseBody annotations is to inform the controller that the returned object has been serialized into Json, the returned value will be bound to HttpResponse body.

Here, Spring HTTP message converters serialize the return value to the type specified in HTTP header.

Q14) What is @ResponseEntity annotation?

Answer: @ResponseEntity, as the name suggests, is an annotation that represents the HTTP response entity. @ResponseEntity contains constructors that allow you to specify status code, body, header, and other information.

Q15) What is @pathVariable?

Answer: @PathVariable annotation is used to directly extract information from the URI.

Q16) What is MediaType?

Answer: MediaType is used to specify the type of data that is to be produced or consumed by the controller. This narrows down and aids with mapping.

Q17) What is REST API?

Answer: Restful API is one of the favorite Spring Boot Interview Questions and Answers of recruiters to interrogate a fresher candidate.

REST API or RESTful API is used to transfer http requests such as Get, Post, Put, and Delete. REST or Representational Transfer is a technology that imitates communication style used for web services.

Q18) What are the types of HTTP methods and Corresponding RestTemplate methods?

Answer:

GET: Read operations

Use: To retrieve the list of customers and use sorting, pagination, and filtering to navigate big lists.

Status codes: 200 – (OK) valid request, 404 – (Not Found) Invalid request.

POST: Location header with link to /customers/{id} containing new ID

Use: To create the newrecord with new id.

Status codes: 201 (Created), 404 (Not Found), 409 (Conflict) if resource already exists.

PUT: To update/replace every resource in the entire collection.

Use: To update/replace data

Status codes: 405 (Method Not Allowed), 200 (OK), or 204 (No Content), 404 (Not Found), in case of ID invalid or not found.

PATCH: unless you want to modify the collection itself.

Use: To update/modify data

Status codes: 405 (Method Not Allowed), 200 (OK), or 204 (No Content), 404 (Not Found), in case of ID invalid or not found.

DELETE: To completely delete the collection – often not desirable

Use: To perform deletion

Status codes: 405 (Method Not Allowed), 200 (OK), or 204 (No Content), 404 (Not Found), in case of ID invalid or not found.

Q19) Difference between POST and PUT methods?

Answer: Basically, Put is used to replace all the target resources with the selected/requested payload. On the other hand, Post method is used to submit or send data to the specific server or resource such as file upload, information, or changing the current status.

An explicitly created object suggest use of the Put method while server-specified name shows the use of Post method.

Put allows you to Put objects more than a single time and also allows creation or updation of resources using the exact object or URL.

On the other hand, Post allows multiple requests at the same time to make changes to an object or URL.

Q20) What is @Autowired annotation and its usage?

Answer: Same as the @Required annotation, @Autowired annotation can be used to bind or autowire bean with the setter method. In other words, one can implicitly define object dependency. It provides developers with control regarding autowiring.

Q21) How many ways the autowired can mode?

Answer:

  • No: It’s the default option. Defining not to autowire, which is set using ref attribute.
  • byName: This makes use of property name for autowiring. If bean name matches other bean property name, autowiring is done.
  • byType: Same way as the byName mode, if the bean data type is shown to be compatible with other bean property, autowiring is done.
  • Constructor: byType mode defined in constructor.
  • Autodetect: Finds the default constructor for autowiring. If not found, byType autowiring is performed.

Q22) What are the limitations of autowiring mode?

Answer:

  • If constructor contains explicit dependencies, they will override autowiring instructions.
  • Possibilities of Overriding: Dependencies can be easily defined using constructor-arg or property tags to override the autowiring.
  • String, integer, and similar data type properties have to be defined manually and cannot be autowired.

Q23) What is spring-boot-starter-data-jpa?

Answer: Spring Boot provides spring-boot-starter-data-jpa, which is one of the Spring Boot Starters, to easily connect relational database with Spring MVC applications.

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

Q24) How does JPA Work?

Answer: JPA stands for Java Persistence API, which is used as an API that allows the developers to work with objects. When you deal with a relational database, you have to make use of SQL statements in order to retrieve information for certain queries. JPA eliminates the need of using SQL statements and allows the developers to deal with objects without SQL statement requisite. Developers can perform actions such as accessing, modifying, managing, and persisting information.

A JPA persistence provider can create a database schema by following the information provided in metadata. Here, JPA metadata has to be defined in the Java class. Metadata can also be defined using XML. JPA can handle both static and dynamic object-based queries.

Q25) What is the difference between JPA and Hibernate?

Answer: While JPA and Hibernate both are completely different entities, they are interconnected in certain ways. JPA is an API that provides developers with specifications and guidelines for implementation. However, it is not an implementation and will require a tool that can implement the specifications.

Consequently, Hibernate comes into picture, which is nothing but a tool that follows the guideline as well as compulsory and optional specifications defined by JPA and makes it functional.

Using Hibernate for JPA implementation also allows you to switch over other implementation tools easily, which is not possible if used Hibernate alone.

Q26) What is spring-boot-starter-test?

Answer: Spring-boot-starter-test is the dedicated testing module of the Spring Boot. It brings the Starter Test Modules and a certain number of libraries to test your application.

Following is the list of libraries in the Spring-boot-starter-test module:

  • Hamcrest
  • JsonPath
  • JUnit
  • AssertJ
  • Mockito
  • Spring Test & Spring Boot Test
  • JSONassert

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

Q27) How to test the Controller class in Spring Boot?

Answer: To test the controller class in Spring Boot, developers have the following 2 alternatives:

  • To use the mock environment or
  • To use an embedded Servlet container.

Q28) What is @RunWith(SpringJUnit4ClassRunner.class)?

@RunWith is an annotation used to define if a class should run along a specific runner class. SpringJUnit4ClassRunner.class is used as Spring Boot makes use of the Spring test. A developer can choose from multiple of runners based on the test.

Q29) What is @ContextConfiguration annotation?

Answer: In order to configure ApplicationContext for tests such as integration, @ContextConfiguration annotation is used. It shows ApplicationContext resource and classes utilized to load it.

@ContextConfiguration calls ClassPathContextConfiguration, which helps to identify the Java classes and ContextLoader to run on JVM.

Same way, AnnotationConfigContextLoader.class is a ContextLoader used to determine the classes to load.

If you are asked to provide an example for @ContextConfiguration during Spring Boot Interview Questions and Answers, use the below code.

A simple example for the @ContextConfiguration annotation:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Sample.class, loader = AnnotationConfigContextLoader.class)
public class JUnitSpringExample {}
Class file:
@Configuration
public class Sample {
@Bean
public SampleService getSampleService() {
return new SampleServiceImpl();
}}

Q30) What is Swagger2?

Answer: Swagger is used to describe the structure of APIs. Swagger 2 is an open source service provided in Spring Boot that makes it easier for the machines to identify the structure of APIs such as RESTful Web services.

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>

Q31) How to integrate the Swagger2?

Answer: Below is a sample for integration of Swagger2 with docket:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}

@EnableSwagger2 annotation is used to enable Swagger 2.

Once Docket bean is specified, select method returns an ApiSelectorBuilder instance. This instance is used to determine how to control the exposed endpoints.

RequestHandlerSelectors and PathSelectors are used to configure predicates for of RequestHandler selection. Lastly, any() method will facilitate the documentation using Swagger.

Above configuration can be used to integrate Swagger2 with a Spring Boot Application.

Leave a Reply

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

Looking for Online Training