50 Spring Boot Interview Questions With Code And References

Looking to ace your Spring Boot interview? In this post, we have compiled a list of 50 frequently asked interview questions on Spring Boot, along with their code solutions and reference links to help you prepare for your next interview.

Whether you are a beginner or an experienced Java developer, these questions cover a wide range of topics from basic Spring Boot concepts to advanced ones such as microservices, security, and testing.

So, let’s get started and sharpen our Spring Boot skills!

Spring Boot Interview Questions

1. What is Spring Boot?

Spring Boot is an open-source Java-based framework that simplifies the development and deployment of stand-alone, production-ready Spring applications by providing sensible defaults and reducing boilerplate code.

This code below sets up a basic Spring Boot application by using the @SpringBootApplication annotation on the main class. The SpringApplication.run() method then starts the application.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/

2. What are the advantages of using Spring Boot?

The advantages of Spring Boot include:

  • Simplified dependency management
  • Automatic configuration
  • Embedded server support
  • Actuator for monitoring and management
  • Easy integration with Spring Ecosystem
  • Faster development process

3. What is a starter dependency in Spring Boot?

A starter dependency is a set of pre-defined dependencies and configurations that help to speed up application development. These are provided by Spring Boot to simplify the inclusion of necessary dependencies for specific functionality.

Here’s an example of adding the “spring-boot-starter-web” dependency to a Maven project:

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

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using.build-systems.starters

What is an embedded server and how is it used in Spring Boot?

An embedded server is a server that is included as a part of your application, running in the same JVM. Spring Boot uses embedded servers like Tomcat, Jetty, or Undertow to simplify deployment, making it easier to create standalone applications without the need for an external server.

The SpringApplication.run() method starts the embedded server and initializes the Spring application context. You can configure the embedded server by adding dependencies to your project, such as spring-boot-starter-tomcat or spring-boot-starter-jetty.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApp {

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

Reference: Spring Boot embedded server

4. How can you create a Spring Boot application using Spring Initializr?

Spring Initializr is a web-based tool that helps in generating a Spring Boot project structure with the necessary dependencies. You can access it at start.spring.io, select your project settings, and download the generated project as a zip file.

  1. Go to the Spring Initializr website at https://start.spring.io/
  2. Select the project options you want for your application, such as the language, packaging, and dependencies.
  3. Click the “Generate” button to generate a project ZIP file.
  4. Extract the ZIP file to a folder on your computer.
  5. Open your preferred IDE (such as IntelliJ IDEA, Eclipse or NetBeans) and select “Import Project” or “Open Project” from the File menu.
  6. Navigate to the folder where you extracted the ZIP file and select the “pom.xml” file to import the project.
  7. Start coding your Spring Boot application!

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#getting-started-first-application.

5. What is the purpose of the @SpringBootApplication annotation?

The @SpringBootApplication annotation is a combination of three other annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan. It simplifies the application’s main class configuration and enables auto-configuration and component scanning.

Reference: https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/SpringBootApplication.html

6. What is auto-configuration in Spring Boot?

Auto-configuration is a feature provided by Spring Boot that automatically configures the application based on the dependencies in the classpath. It simplifies the configuration process, reducing the need for manual configurations.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(MyApp.class, args);
        MyService myService = ctx.getBean(MyService.class);
        myService.doSomething();
    }
}

public class MyService {
    public void doSomething() {
        System.out.println("Doing something...");
    }
}

In this example, I have a Spring Boot application with a single MyService class. Spring Boot’s auto-configuration feature automatically sets up the application context with necessary beans and configurations based on the classpath and application dependencies. In this case, since we haven’t defined any explicit configuration or component scanning, Spring Boot will use its default auto-configuration behavior to set up our MyService bean.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.spring-application.auto-configuration

7. How can you disable a specific auto-configuration in Spring Boot?

You can disable a specific auto-configuration by using the spring.autoconfigure.exclude property in the application.properties or application.yml file, and providing the fully-qualified class name of the auto-configuration you want to exclude.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.spring-application.auto-configuration.excluding-specific-auto-configuration-classes

8. What is the purpose of the application.properties or application.yml file in Spring Boot?

The application.properties or application.yml file is used to define configuration properties for the Spring Boot application. It allows you to customize the behavior of your application, such as defining data source properties or changing the server port.

server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=myuser
spring.datasource.password=mypassword
logging.level.root=INFO

Reference: Common Application Properties

9. What is the Spring Boot Actuator?

Spring Boot Actuator is a sub-project of Spring Boot that provides production-ready features like monitoring, management, and auditing of your application. It exposes various endpoints to monitor application health, metrics, and other details.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready

10. How can you enable the Spring Boot Actuator in your application?

To enable the Spring Boot Actuator, add the spring-boot-starter-actuator dependency to your project’s build file (pom.xml or build.gradle).

Here is a complete how-to.

@SpringBootApplication
public class MyApplication {
 
   public static void main(String[] args) {
      SpringApplication.run(MyApplication.class, args);
   }
 
   @RestController
   public static class MyController {
      
      @GetMapping("/hello")
      public String hello() {
         return "Hello World!";
      }
   }
}

In this example, we have a simple Spring Boot application that exposes a REST endpoint at /hello. When you run this application, you can access this endpoint by sending an HTTP GET request to http://localhost:8080/hello.

Now, let’s add Spring Boot Actuator to this application. First, we need to include the Actuator dependency in our pom.xml file:

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

Once we have included the Actuator dependency, we can access various management endpoints that provide useful information about our application. For example, we can access the /actuator/health endpoint to check the health of our application:

$ curl http://localhost:8080/actuator/health
{"status":"UP"}

11. What are the common Spring Boot Actuator endpoints?

Common Actuator endpoints include:

  • /health: Provides application health information
  • /info: Displays general information about the application
  • /metrics: Shows various metrics of the application
  • /env: Displays environment properties
  • /loggers: Shows and modifies logger levels
  • /trace: Displays trace information

Using the code below you can list all the available Actuator endpoints.

import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Endpoint(id = "endpoints")
public class EndpointsController {

    private final ApplicationContext context;

    public EndpointsController(ApplicationContext context) {
        this.context = context;
    }

    @GetMapping("/endpoints")
    public List<String> getEndpoints() {
        Map<String, Object> beansWithAnnotation = context.getBeansWithAnnotation(Endpoint.class);
        List<String> endpoints = new ArrayList<>();
        beansWithAnnotation.forEach((key, value) -> endpoints.add(key));
        return endpoints;
    }
}

Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-endpoints

12. How can you secure Actuator endpoints?

You can secure Actuator endpoints by integrating Spring Security and configuring authentication and authorization rules for the Actuator endpoints.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .requestMatchers(EndpointRequest.to("info", "health")).permitAll()
            .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ACTUATOR")
            .and().httpBasic();
    }
}

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#production-ready-endpoints-security

13. What is the purpose of profiles in Spring Boot?

Profiles in Spring Boot help in managing different configurations for different environments, such as development, testing, staging, and production. They allow you to activate specific sets of configurations based on the active profile.

@SpringBootApplication
public class MyApplication {

   public static void main(String[] args) {
      SpringApplication app = new SpringApplication(MyApplication.class);
      app.setAdditionalProfiles("prod");
      app.run(args);
   }

   @Bean
   public MyService myService() {
      return new MyServiceImpl();
   }

   @Profile("dev")
   @Bean
   public MyOtherService myOtherService() {
      return new MyOtherServiceImpl();
   }
}

In this example, I use the @Profile annotation to define two different beans, one for the dev profile and one for the default profile. I am also setting the active profile to prod programmatically using the setAdditionalProfiles method of the SpringApplication class.

Check out complete example of using Profiles in Spring Boot.

Reference: Spring Boot Profiles

14. How can you change the default port in a Spring Boot application?

You can change the default port by setting the server.port property in the application.properties or application.yml file.

You can also change the port with Java code as chown below:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class MyApp {

  @Bean
  public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
    return factory -> {
      factory.setPort(8081);
    };
  }

  public static void main(String[] args) {
    SpringApplication.run(MyApp.class, args);
  }
}

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-change-the-http-port

15. What is the difference between @Autowired and @Inject annotations?

Both @Autowired and @Inject are used for dependency injection in Spring. @Autowired is a Spring-specific annotation, while @Inject is a part of the Java CDI (Contexts and Dependency Injection) specification. In Spring Boot, both can be used interchangeably, as Spring supports the CDI specification.

@Service
public class MyService {
    private final MyRepository repository;

    @Inject
    public MyService(MyRepository repository) {
        this.repository = repository;
    }

    // ...
}

@Repository
public class MyRepository {
    // ...
}

Reference: https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans-autowired-annotation

16. What is the difference between @Component, @Service, and @Repository in Spring Boot?

All three annotations are used to define beans in Spring Boot, but they have different purposes and semantics:

  • @Component: A generic annotation used for defining beans, typically for utility classes or classes that do not fit into other categories.
  • @Service: Used for defining service layer beans, which contain business logic.
  • @Repository: Used for defining data access layer beans, such as repositories or DAOs.
@Component
public class MyComponent {
   // implementation details here
}

@Service
public class MyService {
   // implementation details here
}

@Repository
public class MyRepository {
   // implementation details here
}

References

17. How can you run a Spring Boot application using the command line?

You can run a Spring Boot application using the command line by executing the following command: java -jar <your_application_jar_file>.jar.

java -jar my-spring-boot-app.jar

This assumes that you have already built your Spring Boot application into a runnable jar file using a build tool such as Maven or Gradle.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-running-your-application

18. What is the purpose of the @RestController annotation in Spring Boot?

The @RestController annotation is a combination of the @Controller and @ResponseBody annotations. It is used to create RESTful web services in Spring Boot, where the response is serialized directly to the response body instead of being passed through a view resolver.

@RestController
public class HelloController {
 
    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
 
}

@Controller annotation identifies the class as a Spring MVC controller and @ResponseBody indicates that the method return type should be serialized into the response body. By using @RestController, we can eliminate the need for @ResponseBody as it is implied.

Reference: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html

19. What is the purpose of the @RequestMapping annotation in Spring Boot?

The @RequestMapping annotation is used to map web requests to specific handler methods in Spring Boot. It can be applied to both class and method levels and supports specifying HTTP methods, URIs, and media types.

@RestController
@RequestMapping("/api")
public class MyController {

    @GetMapping("/users")
    public List<User> getUsers() {
        // Code to fetch users
    }

    @PostMapping("/users")
    public User createUser(@RequestBody User user) {
        // Code to create a user
    }

}

Reference: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html

20. What is the difference between @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping annotations?

These annotations are shortcuts for the @RequestMapping annotation, used to map specific HTTP methods to handler methods:

  • @GetMapping: Maps to HTTP GET requests
  • @PostMapping: Maps to HTTP POST requests
  • @PutMapping: Maps to HTTP PUT requests
  • @DeleteMapping: Maps to HTTP DELETE requests
@RestController
@RequestMapping("/users")
public class UserController {

    private List<User> users = new ArrayList<>();

    @GetMapping("/{id}")
    public User getUser(@PathVariable int id) {
        return users.get(id);
    }

    @PostMapping("/")
    public void createUser(@RequestBody User user) {
        users.add(user);
    }

    @PutMapping("/{id}")
    public void updateUser(@PathVariable int id, @RequestBody User user) {
        users.set(id, user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable int id) {
        users.remove(id);
    }
}

References

21. How can you handle exceptions in a Spring Boot application?

You can handle exceptions in Spring Boot using the following methods:

  • Using the @ExceptionHandler annotation on a method within a controller to handle specific exceptions
  • Implementing a @ControllerAdvice class to handle exceptions globally across multiple controllers
@ControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = {Exception.class, RuntimeException.class})
    public ResponseEntity<String> handleException(Exception e) {
        return new ResponseEntity<>("An error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

The method takes an Exception parameter, which allows us to access information about the exception that occurred. In this example, we are simply returning a ResponseEntity with an error message and an HTTP status code of 500 (Internal Server Error).

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling.

22. What is a ResponseEntity in Spring Boot?

ResponseEntity is a class used to represent the entire HTTP response, including the status code, headers, and body. It allows you to customize the response returned by a RESTful web service.

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
  
  @GetMapping("/hello")
  public ResponseEntity<String> hello() {
    String message = "Hello, world!";
    return new ResponseEntity<>(message, HttpStatus.OK);
  }
}

Reference: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html

23. What is the role of the CommandLineRunner interface in Spring Boot?

The CommandLineRunner interface is used to execute specific code at the startup of a Spring Boot application. By implementing this interface and overriding its run() method, you can perform actions like initializing data or running a script when the application starts.

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyCommandLineRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // your code here
        System.out.println("Hello, world!");
    }
}

The class MyCommandLineRunner implements the CommandLineRunner interface. The run method is where I put the custom code that I want to execute when the Spring Boot application starts up.

Reference: https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/CommandLineRunner.html

24. How can you externalize configuration in Spring Boot?

Spring Boot allows you to externalize configuration using various methods, such as:

  • Using application.properties or application.yml files
  • Using OS environment variables
  • Using command-line arguments
  • Using JNDI properties

In this example below, I am using the @EnableConfigurationProperties annotation to enable the use of a custom configuration class MyProperties. Here’s how the MyProperties class might look:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties({ MyProperties.class })
public class MyApp {

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config

25. What is Spring Data JPA, and how does it relate to Spring Boot?

Spring Data JPA is a sub-project of Spring Data that provides an abstraction over the Java Persistence API (JPA). It simplifies the creation of data access layers by providing automatic implementations of repositories and query methods. Spring Boot seamlessly integrates with Spring Data JPA, making it easy to use in your applications.

Shown below is a class that uses the Spring Data JPA repository interface.

// Import necessary packages
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

// Define a JPA repository interface for a User entity
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    User findByUsername(String username);
}

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-jpa-and-spring-data

26. How can you enable caching in Spring Boot?

To enable caching in Spring Boot, add the spring-boot-starter-cache dependency to your project and use the @EnableCaching annotation in a configuration class. You can then use the @Cacheable, @CacheEvict, and @CachePut annotations to define caching behavior for specific methods.

In the example below I have created a CacheManager bean that uses a ConcurrentMapCacheManager implementation to manage a cache called “myCache”. I also created a myCache bean that retrieves the “myCache” cache from the cache manager.

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("myCache");
    }

    @Bean
    public Cache myCache(CacheManager cacheManager) {
        return cacheManager.getCache("myCache");
    }
}

Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.caching

27. What is Spring Security, and how can you integrate it with Spring Boot?

Spring Security is a powerful and flexible security framework for Java applications. It provides features like authentication, authorization, and protection against common security vulnerabilities.

To integrate Spring Security with Spring Boot, add the spring-boot-starter-security dependency to your project and configure security settings using Spring Security’s DSL or annotations.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/public/**").permitAll()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER")
                .and()
                .withUser("admin").password("{noop}password").roles("USER", "ADMIN");
    }
}

This configuration sets up basic security for your application with form-based authentication. It defines that any requests to /public/** are allowed for everyone, any requests to /admin/** are only allowed for users with the ADMIN role, and all other requests require authentication. It also defines a login page at /login and a logout page that is accessible to everyone.

References

28. How can you create a custom login page with Spring Security in Spring Boot?

To create a custom login page, you need to configure Spring Security to use your login page and implement a controller that handles login requests. Additionally, create a view (e.g., Thymeleaf or JSP) for the login page and map it to the controller.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
 
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER");
    }
}

In the example above, I have defined a custom login page /login using the loginPage() method of the formLogin() configuration. I have also permitted access to the home page / and /home without authentication using the permitAll() method.

Reference: https://spring.io/guides/gs/securing-web/

29. What is the difference between @Bean and @Component annotations?

Both @Bean and @Component annotations are used to define beans in the Spring context, but they have different uses:

  • @Bean: Used inside a configuration class, usually for defining third-party beans or beans with custom configurations.
  • @Component: A generic annotation for defining beans directly in the class, typically used for classes that do not fit into other categories like @Service or @Repository.

In the example below, MyComponent is annotated with @Component, which is a stereotype annotation that marks the class as a Spring-managed component. This means that Spring will automatically detect and instantiate this component when creating the application context.

On the other hand, MyConfiguration is annotated with @Configuration, which indicates that it contains configuration methods that define Spring beans.

The myBean() method is annotated with @Bean, which is a method-level annotation that marks the method as a producer of a bean. T

his means that Spring will call this method to create the MyBean instance and add it to the application context.

@Component
public class MyComponent {
    // ...
}

@Configuration
public class MyConfiguration {
    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

public class MyApp {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(MyComponent.class, MyConfiguration.class);
        MyComponent myComponent = context.getBean(MyComponent.class);
        MyBean myBean = context.getBean(MyBean.class);
        // ...
    }
}

References

30. How can you use Spring Boot with a NoSQL database?

Spring Boot supports various NoSQL databases through Spring Data projects. For instance, to use Spring Boot with MongoDB, add the spring-boot-starter-data-mongodb dependency to your project and configure the database connection properties in the application.properties or application.yml file.

Let’s look at an example where I will connect with MongoDB.

First, add the MongoDB driver to your project’s dependencies. In your pom.xml file, add the following dependency:

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

Next, configure Spring to connect to your MongoDB instance. Add the following to your application.properties file:

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=mydatabase

Replace localhost and 27017 with the hostname and port of your MongoDB instance, and replace mydatabase with the name of your database.

Now you can create a repository interface for your data objects. For example, if you have a Person object, you can create a PersonRepository interface like this:

import org.springframework.data.mongodb.repository.MongoRepository;

public interface PersonRepository extends MongoRepository<Person, String> {

}

The MongoRepository interface provides basic CRUD operations for your objects.

Finally, you can use your repository in your application code:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Autowired
    private PersonRepository personRepository;

    public void savePerson(Person person) {
        personRepository.save(person);
    }

    public Person getPerson(String id) {
        return personRepository.findById(id).orElse(null);
    }

}

This MyService class uses the PersonRepository to save and retrieve Person objects.

References: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-mongodb.

31. What is the difference between a monolithic and a microservices architecture?

A monolithic architecture is a single, unified application containing all the modules and components, while a microservices architecture consists of multiple, small, and loosely coupled services that communicate with each other. Microservices offer better scalability, maintainability, and flexibility compared to monolithic applications.

32. How can you create a microservices architecture using Spring Boot and Spring Cloud?

Spring Boot and Spring Cloud provide various tools and libraries to create microservices architectures, such as:

  • Spring Cloud Netflix for service discovery (Eureka), circuit breaking (Hystrix), and intelligent routing (Zuul)
  • Spring Cloud Config for centralized configuration management
  • Spring Cloud Gateway for API gateway and routing
  • Spring Cloud Sleuth and Zipkin for distributed tracing
  • Spring Cloud Stream for event-driven microservices

Here is an example. First create a new Spring Boot application using the Spring Initializr, and select the dependencies for Spring Web, Spring Data JPA, and any other dependencies you may need for your microservice.

Once you have created your microservices, you can use Spring Cloud to manage the communication between them. Spring Cloud provides a number of tools and frameworks for building microservices, such as service discovery, load balancing, and circuit breaking.

One of the most important components of Spring Cloud is the Eureka server, which is used for service discovery. You can create a Eureka server by adding the spring-cloud-starter-netflix-eureka-server dependency to your project and then configuring it in your application.yml file:

server:
  port: 8761

spring:
  application:
    name: eureka-server

eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: false
    fetchRegistry: false
    serviceUrl:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

This configuration will start a Eureka server on port 8761 and register the microservices with it. You can then configure your microservices to discover each other using Eureka. You can add the spring-cloud-starter-netflix-eureka-client dependency to your microservice and then configure it in your application.yml file:

spring:
  application:
    name: microservice1

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

This configuration will register the microservice with the Eureka server and allow it to discover other microservices.

Reference: https://spring.io/projects/spring-cloud.

33. What is Spring Boot DevTools, and what are its benefits?

Spring Boot DevTools is a set of tools provided by Spring Boot to improve the developer experience during local development. Some of its benefits include:

  • Automatic application restart on code changes
  • LiveReload support for refreshing browser content
  • Improved caching behavior for static resources
  • Remote debugging and development for applications running in VMs or containers

Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-devtools.

34. What are the different types of dependency injection in Spring Boot?

Spring Boot supports three types of dependency injection:

  • Constructor based
  • Method based
  • Setter based

In the code below you will find examples of all of these dependency injections.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {
  
  @Autowired
  private MyDependency myDependency;

  // Constructor Injection
  @Autowired
  public MyComponent(MyDependency myDependency) {
      this.myDependency = myDependency;
  }

  // Setter Injection
  @Autowired
  public void setMyDependency(MyDependency myDependency) {
      this.myDependency = myDependency;
  }

  // Method Injection
  @Autowired
  public void someMethod(MyDependency myDependency) {
      // use myDependency
  }
  
  // ...
}
  1. Constructor Injection: Here, the dependency is injected through a constructor. In the code above, we have a constructor that takes MyDependency as a parameter and the @Autowired annotation ensures that Spring Boot injects the dependency automatically.
  2. Setter Injection: Here, the dependency is injected through a setter method. In the code above, we have a setter method setMyDependency that takes MyDependency as a parameter and the @Autowired annotation ensures that Spring Boot injects the dependency automatically.
  3. Method Injection: Here, the dependency is injected through a regular method. In the code above, we have a method someMethod that takes MyDependency as a parameter and the @Autowired annotation ensures that Spring Boot injects the dependency automatically.

Reference: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-dependencies.

35. How can you create a scheduled task in Spring Boot?

To create a scheduled task in Spring Boot, use the @EnableScheduling annotation in a configuration class and the @Scheduled annotation on the method you want to execute periodically. You can configure the task’s execution frequency using cron expressions or fixed delays.

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTask {

    @Scheduled(fixedDelay = 5000) // runs every 5 seconds
    public void myTask() {
        // code to be executed periodically
    }
}

This example creates a Spring component that contains a method annotated with @Scheduled. The fixedDelay attribute specifies the delay between executions of the task in milliseconds. In this example, the task will be executed every 5 seconds.

Reference: https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#scheduling

36. How can you deploy a Spring Boot application to a cloud platform?

You can deploy a Spring Boot application to cloud platforms like AWS, Google Cloud Platform, or Heroku by following platform-specific guidelines and leveraging platform services, such as AWS Beanstalk, Google App Engine, or Heroku Platform.

References

37. What is the purpose of the @Value annotation in Spring Boot?

The @Value annotation is used to inject values from external sources, like configuration files or environment variables, into fields or method parameters in Spring Boot.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {

  @Value("${my.property}")
  private String myProperty;

  public void doSomething() {
    System.out.println("The value of my.property is: " + myProperty);
  }
}

In this example, the @Value annotation is used to inject the value of a Spring property called my.property into a field called myProperty within the MyComponent class. The value of the property is determined by looking up the value of the ${my.property} placeholder in the Spring environment.

Reference: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Value.html

38. How can you use Spring Boot Test to test a specific layer or slice of your application?

Spring Boot Test provides test slice annotations that allow you to test specific layers or slices of your application in isolation, such as:

  • @WebMvcTest: For testing the web layer (controllers)
  • @DataJpaTest: For testing the data access layer (repositories)
  • @RestClientTest: For testing REST clients
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MyControllerTests {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testController() throws Exception {
        mockMvc.perform(get("/my-endpoint"))
            .andExpect(status().isOk())
            .andExpect(content().string("Hello, World!"));
    }
}

Use the @SpringBootTest annotation to start up a Spring context for testing. @AutoConfigureMockMvc annotation is also used to auto-configure a MockMvc instance for testing our REST endpoints.

IN this example, MockMvc is being used to perform an HTTP GET request to the /my-endpoint endpoint of our application. Then using the andExpect method to verify that the response has an HTTP status code of 200 OK and a response body of “Hello, World!”.

To test a specific layer or slice of your application, you can use the @WebMvcTest, @DataJpaTest, or @RestClientTest annotations instead of @SpringBootTest. These annotations will start up a smaller slice of your application context that is specific to the layer you are testing.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing

39. What is Spring Boot Test, and what are its benefits?

Spring Boot Test is a testing module provided by Spring Boot that simplifies the testing process for Spring Boot applications. It offers features like auto-configuration, test slice annotations, and integration with popular testing frameworks, making it easier to write unit and integration tests.

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.jdbc.Sql;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Sql("/test-data.sql")
public class UserRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private UserRepository userRepository;

    @Test
    public void whenFindByUsername_thenReturnUser() {
        // given
        User user = new User("[email protected]", "password");
        entityManager.persist(user);
        entityManager.flush();

        // when
        User foundUser = userRepository.findByUsername(user.getUsername());

        // then
        assertThat(foundUser.getUsername())
                .isEqualTo(user.getUsername());
    }
}

In this example, I have a test class for a Spring Boot application that uses JPA and an SQL database. The class is annotated with @DataJpaTest, which tells Spring Boot to set up an in-memory database and configure the application context with the necessary JPA beans.

The test method whenFindByUsername_thenReturnUser() tests the findByUsername() method of a UserRepository class. It uses the TestEntityManager to persist a user object to the database and then calls the repository method to retrieve the user. Finally, it uses the assertThat() method from the AssertJ library to compare the retrieved user object with the original object.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing.

40. What is the difference between @MockBean and @Autowired in the context of testing?

In the context of testing, both @MockBean and @Autowired are used for injecting dependencies, but with different purposes:

  • @MockBean: Creates a mock instance of a bean using a mocking framework (e.g., Mockito) and injects it into the test context.
  • @Autowired: Injects an actual bean instance from the application context into the test context.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.junit.jupiter.api.Test;

@SpringBootTest
public class MyServiceTest {
 
    @Autowired
    private MyService myService;
 
    @MockBean
    private MyRepository myRepository;
 
    @Test
    public void myTest() {
        // Test code here
    }
}

In this example, @Autowired is used to inject an instance of MyService into the test class, while @MockBean is used to create a mock instance of MyRepository.

The key difference between the two annotations is that @Autowired is used to inject real instances of beans into a test, while @MockBean is used to create mock instances of beans for testing purposes.

@MockBean is particularly useful for testing services that depend on other services or repositories, as it allows you to isolate the behavior of the service being tested by mocking its dependencies.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-with-mock-environment

41. How can you test a RESTful web service in Spring Boot?

You can test a RESTful web service in Spring Boot using tools like Spring Boot Test with the @WebMvcTest annotation and the MockMvc class for simulating HTTP requests and asserting responses.

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@WebMvcTest
public class MyControllerTest {
  
  @Autowired
  private MockMvc mockMvc;

  @Test
  public void testGet() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/api/myresource")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().json("{\"message\": \"Hello world!\"}"));
  }
}

In this example, I am using the @WebMvcTest annotation to test a controller class called MyController. I am also using MockMvc to make a GET request to the /api/myresource endpoint and checking that the response has an HTTP status of 200 (OK) and a JSON body containing the message “Hello world!”.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing.

42. How can you create a custom configuration in Spring Boot?

To create a custom configuration in Spring Boot, create a class annotated with @Configuration and define your custom beans using the @Bean annotation.

First, create a new class and annotate it with @Configuration and @PropertySource to specify the properties file that contains your configuration values. For example:

@Configuration
@PropertySource("classpath:myapp.properties")
public class MyAppConfiguration {
 
    @Autowired
    private Environment env;
 
    @Bean
    public MyBean myBean() {
        MyBean myBean = new MyBean();
        myBean.setSomeProperty(env.getProperty("myapp.someProperty"));
        myBean.setAnotherProperty(env.getProperty("myapp.anotherProperty"));
        return myBean;
    }
 
}

In this example, I am creating a MyAppConfiguration class and telling Spring Boot to look for properties in a file named myapp.properties. I am also defining a myBean() method that creates and configures a MyBean instance using values from the properties file.

Note that I am using the Environment object to get the values of our properties. This object is automatically injected by Spring Boot and provides a way to access properties from various sources.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config

43. What is the purpose of the @Conditional annotation in Spring Boot?

The @Conditional annotation is used to define conditional bean creation based on specific conditions, such as the presence or absence of other beans, classes , or properties. It helps in creating beans that should only be created when certain conditions are met.

@Configuration
public class MyConfiguration {
 
    @Bean
    @Conditional(OnProductionEnvironment.class)
    public MyService myService() {
        return new MyProductionService();
    }
 
    @Bean
    @Conditional(OnDevelopmentEnvironment.class)
    public MyService myService() {
        return new MyDevelopmentService();
    }
}

public class OnProductionEnvironment implements Condition {
 
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String environment = context.getEnvironment().getProperty("spring.profiles.active");
        return environment != null && environment.equalsIgnoreCase("prod");
    }
}

public class OnDevelopmentEnvironment implements Condition {
 
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String environment = context.getEnvironment().getProperty("spring.profiles.active");
        return environment != null && environment.equalsIgnoreCase("dev");
    }
}

In this example, theree are two implementations of the MyService interface – one for the production environment and one for the development environment. I use the @Conditional annotation to conditionally create and register the appropriate bean based on the value of the spring.profiles.active property.

The @Conditional annotation is used to specify a condition that must be met for a bean to be created and registered. The matches() method of this class is called to determine whether the condition is met. If the condition is met, the bean is created and registered; otherwise, it is not.

Reference: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Conditional.html

44. What are the different types of events supported by Spring Boot?

Spring Boot supports various types of events, including:

  • Application events: Predefined events like ApplicationStartedEvent, ApplicationReadyEvent, and ApplicationFailedEvent.
  • Custom events: User-defined events that can be published and consumed within the application using the ApplicationEventPublisher and @EventListener annotations.
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;

public class EventListener implements ApplicationListener<ApplicationStartedEvent> {
    
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        System.out.println("ApplicationStartedEvent received");
    }

    @EventListener
    public void handleContextRefreshedEvent(ContextRefreshedEvent event) {
        System.out.println("ContextRefreshedEvent received");
    }

    @EventListener
    public void handleContextStartedEvent(ContextStartedEvent event) {
        System.out.println("ContextStartedEvent received");
    }

    @EventListener
    public void handleContextStoppedEvent(ContextStoppedEvent event) {
        System.out.println("ContextStoppedEvent received");
    }

    @EventListener
    public void handleContextClosedEvent(ContextClosedEvent event) {
        System.out.println("ContextClosedEvent received");
    }
}

This code shows an example of an event listener class that listens for different types of events that Spring Boot supports, such as ApplicationStartedEvent, ContextRefreshedEvent, ContextStartedEvent, ContextStoppedEvent, and ContextClosedEvent.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-application-events-and-listeners

45. How can you customize the JSON serialization and deserialization in Spring Boot?

To customize JSON serialization and deserialization in Spring Boot, you can configure an ObjectMapper bean with custom settings, or use Jackson annotations like @JsonSerialize, @JsonDeserialize, and @JsonFormat on your domain classes.

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class AppConfig {

    @Bean
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.build();
        // Customize the ObjectMapper
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return objectMapper;
    }

}

In the example above, I created a custom ObjectMapper bean using the Jackson2ObjectMapperBuilder provided by Spring Boot. You can customize the ObjectMapper by calling its various configuration methods, such as configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) to disable the failure on unknown properties.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.json.serialization.

46. What is the purpose of the @Lazy annotation in Spring Boot?

The @Lazy annotation is used to create lazy-initialized beans in Spring Boot. A lazy-initialized bean is created only when it is first requested, instead of being created at the startup of the application. This can help reduce startup time and memory usage for beans that are not always needed.

@Component
@Lazy
public class MyLazyBean {
    public MyLazyBean() {
        System.out.println("MyLazyBean instantiated.");
    }
}

References: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Lazy.html

Conclusion

In this post, I have covered 46 important interview questions related to Spring Boot, along with relevant code examples and reference links to official documentation.

Also check part 2 and part 3 of the Spring Boot interview questions series.