Spring Boot interview questions and answers

1. What is Spring Boot?

Spring Boot is a module in Java Spring framework. We can say it is an open-source Java-based framework used to develop standalone, web & enterprise application, production-grade Spring-based applications with minimal effort. It provides a streamlined way to set up and configure Spring-based applications quickly, with defaults for many aspects of the application setup, so developers can focus more on writing business logic and less on configuration.

2. What are the key features of Spring Boot?

  • a) Auto-configuration: Spring Boot automatically configures the Spring application based on dependencies added to the project's classpath, reducing the need for manual configuration.
  • b) Standalone: Spring Boot applications can be run as standalone JAR files, which contain an embedded web server (like Tomcat, Jetty, or Undertow), eliminating the need for deploying the application on a separate server.
  • c) Starter dependencies: Spring Boot provides a wide range of "starter" dependencies, which are pre-configured sets of dependencies for specific functionalities (e.g., web applications, data access, security), making it easy to include common dependencies in your project.
  • d) Actuator: Spring Boot Actuator provides built-in production-ready features to monitor and manage Spring Boot applications, such as health checks, metrics, and environment information, which are exposed via RESTful endpoints.
  • e) Spring Boot CLI: Spring Boot CLI (Command Line Interface) allows developers to quickly prototype and develop Spring Boot applications using a command-line interface.
  • f) Spring Boot DevTools: DevTools provide features like automatic application restart, live reload, and remote debugging, improving the development

Overall, Spring Boot simplifies the process of building and deploying Spring-based applications, allowing developers to focus more on writing business logic and less on boilerplate configuration.

3. What is @SpringBootApplication annotation?

Spring boot @SpringBootApplication annotation represent that the corresponding application is a spring boot application. It is working for three annotations like @Configuration, @EnableAutoConfiguration, and @ComponentScan.

@Configuration : It is a class level annotation indicating that an object is a source of bean definitions. @Configuration classes declare beans through @Bean annotated method.

@EnableAutoConfiguration : It enables to spring boot to auto-configure the application context. So it automatically creates and registers beans based on both the included jar files in the class path and the beans defined by us.

@ComponentScan : It is used for auto detecting and registering spring managed components like beans, controllers, repository, services etc.

4. What is controller in spring boot and what is the role of a controller component in a spring boot application?

In Spring Boot context, a controller is a class that handles incoming HTTP requests and generates an appropriate HTTP response. Controllers are a fundamental part of the Spring MVC (Model-View-Controller) architecture, which is widely used for building web applications in Java.

Here's a breakdown of the key aspects of controllers in Spring Boot:

Annotation: Controllers are typically annotated with @Controller or @RestController. The @Controller annotation indicates that the class serves as a controller and is capable of handling HTTP requests, while @RestController is a specialized version of @Controller that combines the @Controller and @ResponseBody annotations, meaning it returns data directly in the response body, typically in JSON or XML format.

Request Mapping: Within a controller class, methods are annotated with @RequestMapping (or its shortcut annotations like @GetMapping, @PostMapping, etc.) to specify which HTTP requests they should handle. The @RequestMapping annotation maps HTTP requests to handler methods based on the request path, method, parameters, headers, etc.

Handler Methods: Handler methods are the methods within the controller class that handle incoming HTTP requests. These methods perform necessary processing, such as fetching data from a database, invoking business logic, or delegating tasks to other components, and then return an appropriate HTTP response, often by returning a view name, model, or a response body object.

Request Parameters and Path Variables: Controller methods can accept parameters from the HTTP request, such as query parameters, path variables, request headers, etc. Spring Boot automatically binds these parameters to method parameters using annotations like @RequestParam, @PathVariable, @RequestHeader, etc.

Here's a simple example of a controller in Spring Boot:

                                        
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String sayHello(@RequestParam(name = "name", required =
    false, defaultValue = "World") String name) {
        return "Hello, " + name + "!";
    }
}
                                        
                                    

5. What is the difference between @Controller and @RestController in spring boot?

In Spring Boot, both @Controller and @RestController are annotations used to define classes that handle incoming HTTP requests. However, they serve slightly different purposes:

@Controller:

The @Controller annotation is a generic annotation indicating that a class serves as a controller in a Spring MVC application.

Controllers annotated with @Controller typically handle HTTP requests and generate a response that may include a view name or model attributes.

These controllers are typically used in applications where the response might be HTML pages rendered by a view resolver, or where the application requires serverside rendering of templates.

@RestController:

The @RestController annotation is a specialized version of @Controller that is introduced in Spring 4.0. It combines the functionality of @Controller and @ResponseBody.

Controllers annotated with @RestController are responsible for handling HTTP requests and returning the response directly in a format suitable for RESTful APIs, typically JSON or XML.

Methods within @RestController classes automatically serialize return values to the HTTP response body using message converters, eliminating the need for an explicit @ResponseBody annotation on each method.

@RestController is commonly used in applications that primarily serve data to client-side applications or APIs, where responses are typically in the form of JSON or XML.

6. What is the difference between @RequestMapping and @GetMapping in spring boot?

In Spring Boot, both @RequestMapping and @GetMapping are annotations used to map HTTP requests to handler methods in controller classes. However, they differ in terms of specificity and convenience:

@RequestMapping:

The @RequestMapping annotation is a generic annotation used to map HTTP requests to handler methods in a controller class.

It can be applied at the class level to specify a base URI for all request mapping methods within the class, as well as at the method level to define more specific mappings.

With @RequestMapping, you can specify various attributes such as the request method (GET, POST, PUT, DELETE, etc.), request parameters, headers, content types, etc.

@GetMapping:

The @GetMapping annotation is a specialized form of @RequestMapping introduced in Spring 4.3. It is specifically used to map HTTP GET requests to handler methods.

It is a shortcut for @RequestMapping(method = RequestMethod.GET), providing a more concise and readable way to define request mappings for GET requests.

@GetMapping is useful when you want to map a handler method to a specific URL path using the GET HTTP method, without having to explicitly specify the method attribute.

Let’s see the following code for better understanding;

Using @RequestMapping:

@Controller
@RequestMapping("/example")
public class ExampleController {

@RequestMapping(value = "/path", method = RequestMethod.GET)
public String handleGetRequest() {
// Handle GET request
return "silanSoftware";
}
}

Using @GetMapping:

@Controller
@RequestMapping("/example")
public class ExampleController {

@GetMapping("/path")
public String handleGetRequest() {
// Handle GET request
return "silanSoftware";
}
}

In the above examples, both approaches achieve the same result. However, @GetMapping provides a more concise syntax for mapping GET requests to handler methods, making the code easier to read and maintain.

7. What is JPA(Java Persistency API) in spring boot?

In Spring Boot, JPA (Java Persistence API) is a standard specification for accessing, managing, and persisting data between Java objects/entities and a relational database. It provides a set of APIs and guidelines for developers to perform CRUD (Create, Read, Update, Delete) operations on database entities using object-oriented programming paradigms.

Spring Boot offers seamless integration with JPA through its Spring Data JPA module, which simplifies the implementation of data access layers in Spring applications.

8. How Spring Boot auto configuration work?

Spring Boot's auto-configuration is based on the use of Spring Framework's @Conditional annotation, which allows for the creation of beans based on certain conditions, such as the presence of specific properties or libraries on the classpath.

Spring Boot itself can be thought of as a shared context configuration with many @Conditionals that create various beans depending on the presence of specific properties or libraries.

For example, when the main method of a Spring Boot application is run, Spring Boot will automatically register a number of PropertySources to read in properties from various locations. These properties can then be used to conditionally create beans.

Here is an example of a simple @Conditional that creates a bean based on the presence of a specific property:

@Configuration
public class ExampleConfiguration {

@Bean
@Conditional(MyCondition.class)
public ExampleBean exampleBean() {
return new ExampleBean();
}

static class MyCondition implements Condition {

@Override

public boolean matches(ConditionContext context,
AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
return environment.containsProperty("example.property");
}
}
}

In this example, the ExampleBean will only be created if the property example.property is present in the environment.

Spring Boot includes many built-in @Conditionals for common cases, such as the presence of certain libraries on the classpath or the existence of specific properties. These conditionals allow Spring Boot to automatically configure and create beans for things like data sources, web servers, and more.

9. What is the purpose of SpringDevTools in spring boot?

The primary purpose of Spring DevTools is to improve the development experience by automatically detecting changes in the application's source code and triggering a restart of the application. This can save developers time as they don't have to manually restart the application every time they make a change.

To use Spring DevTools, you need to add the spring-boot-devtools dependency to your project. In a Maven project, you can do this by adding the following dependency to your pom.xml file:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>

10. What is the use of application.properties file in spring boot?

In Spring Boot, the application.properties file (or alternatively, application.yml) is used for external configuration of the application. It allows developers to configure various aspects of the Spring Boot application, such as database connection settings, server port, logging levels, and other application properties. Here's a breakdown of its use:

server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=Silan@123

11. What is repository in spring boot?

In Spring Boot application development context, repository is an interface which must extends JpaRepository or CrudRepository.

That means to represent a repository, we create an interface which extends from JpaRepository. JpaRepository containing some built in methods which are invoking for performing some database operations. It is a mechanism for accessing and managing data persistence. It typically represents a layer in the application responsible for performing CRUD (Create, Read, Update, Delete) operations on entities (data objects) stored in a database.

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {

User findByUsername(String username);

List<User> findByAgeGreaterThan(int age);

// Other custom query methods...
}

In this example, UserRepository is a Spring Data JPA repository interface responsible for managing User entities. It extends the JpaRepository interface and defines additional query methods like findByUsername and findByAgeGreaterThan, which Spring Data JPA automatically implements based on method name conventions.

12. What is the difference between CrudRepository and JpaRepository in spring boot?

In Spring Boot, both CrudRepository and JpaRepository are interfaces provided by Spring Data for performing CRUD (Create, Read, Update, Delete) operations on entities in a database. However, they differ in terms of the additional functionality and features they provide:

CrudRepository:

CrudRepository is a basic repository interface provided by Spring Data. It provides CRUD operations (save, findById, findAll, delete, etc.) for managing entities.

It's a more generic interface that doesn't assume any particular persistence mechanism, making it suitable for use with various data storage technologies, including relational databases, NoSQL databases, in-memory databases, etc.

JpaRepository:

JpaRepository is a subinterface of CrudRepository provided by Spring Data JPA It extends CrudRepository and provides additional JPA-specific methods for working with JPA entities and executing JPA queries.

It's specifically designed for use with JPA (Java Persistence API) and is tailored for working with JPA entity managers and repositories.

13. What is the use of service component in spring boot application development?

In a Spring Boot application, the @Service annotation is used to mark a class as a service component. Service components are typically used to encapsulate business logic and provide an interface for other components to interact with.

Here is an example of a simple service component in a Spring Boot application:

@Service
public class MyService {

public String doSomething() {
// Business logic goes here
return "Hello, world!";
}
}

In this example, the MyService class is marked as a service component using the @Service annotation. This allows Spring to automatically detect the component and register it as a bean in the application's context.

14. What is ResponseEntity in spring boot?

In Spring Boot, ResponseEntity is a class that represents the entire HTTPn response, including the status code, headers, and body. It is often used to build custom HTTP responses in a Spring Boot application.

Here is an example of using ResponseEntity to build a custom HTTP response in a Spring Boot application:

@RestController
public class MyController {

@GetMapping("/example")
public ResponseEntity<String> example() {
HttpHeaders headers = new HttpHeaders();
headers.add("My-Header", "My-Value");
return
ResponseEntity.status(HttpStatus.OK).headers(headers).body("Hello,
world!");
}
}

In this example, the example() method returns a ResponseEntity<String> object. This object is constructed by calling the ResponseEntity.status() method with the desired HTTP status code, the ResponseEntity.headers() method with the desired headers, and the ResponseEntity.body() method with the desired body.

When the example() method is called, Spring Boot will automatically convert the ResponseEntity<String> object to an HTTP response and send it back to the client.

15. What is @PathVariable in spring boot?

In Spring Boot, the @PathVariable annotation is used to bind a method parameter to a path variable in a URL.

Here is an example of using @PathVariable to extract a path variable from a URL in a Spring Boot application:

@RestController
public class MyController {

@GetMapping("/example/{id}")
public String example(@PathVariable Long id) {
// Use the 'id' variable
return "Example with id: " + id;
}
}

In this example, the example() method is mapped to the URL/example/{id}, where {id} is a path variable. The @PathVariable annotation is used to bind the id method parameter to the {id} path variable. When this URL is accessed, the value of the {id} path variable is passed to the example() method as the id parameter.

16. What is the purpose of @PostMapping annotation in spring boot?

The @PostMapping annotation in Spring Boot is used to map a HTTP request with the HTTP method POST to a specific method in a controller class. It is a shortcut for @RequestMapping(method = RequestMethod.POST).

Here is an example of using @PostMapping to handle a POST request in a Spring Boot application:

@RestController

public class MyController {

@PostMapping("/example")
public String example(@RequestBody MyRequestBody request) {
// Process the request
return "Example processed!";
}
}

In this example, the example() method is mapped to the URL /example with the HTTP method POST. When a POST request is made to this URL, the example() method will be called and the MyRequestBody object will be passed as the request parameter.

@PostMapping is a part of the Spring MVC framework, which is included in Spring Boot. It is available in any Spring MVC application, not just Spring Boot.

It's important to note that @PostMapping can only be used with HTTP methods that support the POST method, such as POST. It cannot be used with methods like GET, which do not support the POST method.


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 Previous