25 Spring Boot Interview Questions with Code and References – Part 3

This is the second part of the Spring Boot Interview Questions series. In this post, I have compiled a list of 47 additional frequently asked interview questions on Spring Boot, along with their code solutions and reference links to help you prepare for your next interview.

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

Spring Boot Interview Questions

1. How can you configure caching in Spring Boot?

To configure caching in Spring Boot, add the spring-boot-starter-cache dependency, enable caching using the @EnableCaching annotation in a configuration class, and define cacheable methods using the @Cacheable, @CachePut, and @CacheEvict annotations.

1. Add Caching Dependency

Include the caching dependency in your pom.xml (for Maven) or build.gradle (for Gradle):

For Maven:

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

For Gradle:

Groovy
implementation 'org.springframework.boot:spring-boot-starter-cache'

2. Enable Caching

In your main application class, annotate it with @EnableCaching. This annotation enable caching support in a Spring Boot applicaiton.

Java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class YourApplication {

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

3. Configure a cache manager (optional)

By default, Spring Boot uses a simple in-memory cache manager. However, for this example I will create a custom CacheManager bean to use EhCache:

Java
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
@EnableCaching
public class CachingConfig {

    @Bean
    @Primary
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheCacheManager().getObject());
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheCacheManager() {
        EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean();
        cacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
        cacheManagerFactoryBean.setShared(true);
        return cacheManagerFactoryBean;
    }
}

Note: You can also use other cache managers like Caffeine and Redis.

4. Use @Cacheable Annotation

Now you can use cache annotations in your service methods. For example:

Java
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Cacheable("myCache")
    public String getData(String key) {
        // Your business logic here
        return "Data for key: " + key;
    }
}

The @Cacheable annotation indicates that the result of the method will be cached with the name “myCache.” Subsequent calls with the same arguments will return the cached result without executing the method.

Reference: Spring Boot Caching

2. What is the purpose of the @SessionAttributes annotation in Spring Boot?

The @SessionAttributes annotation is used to store model attributes in the HTTP session, allowing them to persist across multiple requests. It is useful for maintaining user-specific data, such as form data or user preferences, during a user session.

It’s important to note that @SessionAttributes is not intended for long-term storage of attributes; it’s tied to the user’s session and is typically cleared when the session ends. For more persistent storage, consider using other mechanisms like a database or some form of client-side storage.

Let me show you and example using @SessionAttributes.

1. Create a Controller to use a SessionAttribute

In code shown below, the initializeMyObject method is annotated with @ModelAttribute("myAttribute"), indicating that the myAttribute attribute should be stored in the session.

Java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@SessionAttributes("myAttribute")
public class MyController {

    @ModelAttribute("myAttribute")
    public MyObject initializeMyObject() {
        // Initialize and return an object
    }

    @GetMapping("/my-page")
    public String myPage() {
        // Controller logic
        return "my-page";
    }
}

2. At the method level

You can also use @SessionAttributes at the method level to declare model attributes that should be stored in the session for a specific request mapping. Check out my code below showing such use:

Java
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@SessionAttributes("myAttribute")
public class MyController {

    @GetMapping("/my-page")
    @ModelAttribute("myAttribute")
    public MyObject myPage() {
        // Initialize and return an object
    }

    // Controller logic...
}

Note: The myAttribute attribute will be stored in the session for requests mapped to the /my-page endpoint.

Reference: Spring Boot Session Attributes

3. How can you implement internationalization (i18n) in Spring Boot?

To implement internationalization in Spring Boot, configure a LocaleResolver and a MessageSource bean in a configuration class. Use the messages.properties files in the src/main/resources directory to store localized messages for each supported locale.

In your controllers and templates, use the MessageSource or message tags to display localized messages based on the current locale.

Let me show you an example:

1. Add dependencies

Ensure that you have the necessary dependencies in your pom.xml (for Maven) or build.gradle (for Gradle) file:

For Maven:

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

For Gradle:

Groovy
implementation 'org.springframework.boot:spring-boot-starter-web'

2. Configure messages sources

In your application.properties or application.yml, configure the base names of the properties files that contain your messages.

Plaintext
# Default locale
spring.messages.basename=messages
spring.messages.encoding=UTF-8

This assumes you have a messages.properties file in the classpath. Create additional files for other locales, such as messages_fr.properties for French.

3. Create message properties files

Create properties files for each supported locale. For example, messages.properties:

Plaintext
greeting.message=Hello, welcome to our application!

And messages_fr.properties:

Plaintext
greeting.message=Bonjour, bienvenue dans notre application!
4. Use MessageSource in your code

Inject the MessageSource bean into your service or controller and use it to retrieve messages based on the user’s locale:

Java
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

@Service
public class GreetingService {

    private final MessageSource messageSource;

    public GreetingService(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    public String getGreeting() {
        return messageSource.getMessage("greeting.message", null, LocaleContextHolder.getLocale());
    }
}

5. Expose Locale change endpoint (optional)

If you want to allow users to change their locale dynamically, you can expose an endpoint to handle locale changes. For example:

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

import java.util.Locale;

@RestController
public class LocaleController {

    @GetMapping("/change-locale")
    public void changeLocale(@RequestParam String lang) {
        LocaleContextHolder.setLocale(new Locale(lang));
    }
}

6. Viewing Internationalized text

Run your Spring Boot application. You can Access it with different locales to see the messages change.

Example below show the use with Thymeleaf:

HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Internationalization Example</title>
</head>
<body>
    <h1 th:text="#{greeting.message}">Hello, welcome to our application!</h1>
</body>
</html>

Reference: Spring Boot Internationalization

4. What is the difference between @Value and @ConfigurationProperties in Spring Boot?

Both @Value and @ConfigurationProperties annotations are used to bind external configuration properties to Java objects, but they have different use cases and features:

  • @Value: Used to inject single configuration properties or expressions into fields or method parameters.
  • @ConfigurationProperties: Used to bind multiple configuration properties to a class, providing features like validation, type conversion, and property nesting.

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

5. How can you configure a custom error page in Spring Boot?

To configure a custom error page in Spring Boot, create an HTML, Thymeleaf, or other template file with the error content and place it in the src/main/resources/templates/error directory. Spring Boot will automatically use this template for error handling. Alternatively, you can create a custom error controller by implementing the ErrorController interface and registering it as a bean.

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

6. What is the purpose of the @Primary annotation in Spring Boot?

The @Primary annotation is used to indicate the primary bean when multiple beans of the same type are defined in the application context. It helps resolve ambiguity during autowiring by giving higher precedence to the primary bean.

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

7. How can you create a fat JAR or executable JAR in Spring Boot?

To create a fat JAR or executable JAR in Spring Boot, use the Spring Boot Maven Plugin or Spring Boot Gradle Plugin in your project’s build configuration.

The plugins will package the application and its dependencies into a single JAR file with a manifest that includes the SpringApplication class as the main class.

With Maven

In your pom.xml, make sure you have the Spring Boot Maven Plugin configured:

XML
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Now build the jar:

Bash
mvn clean install

This will generate a JAR file with a name like your-application-name-<version>.jar in the target directory.

Using Gradle

In your build.gradle, apply the Spring Boot plugin:

Groovy
plugins {
    id 'org.springframework.boot' version '2.5.5'
}

Now build the application:

Bash
./gradlew clean build

Running the executable JAR

Once I created the the executable JAR, I run it using the following command:

Bash
java -jar your-application-name-<version>.jar

Reference: Spring Boot Executable Jar

8. What is the purpose of the @Service annotation in Spring Boot?

The @Service annotation is used to define a service layer class, indicating that the class is responsible for business logic and processing. It is a specialized version of the @Component annotation, providing semantic meaning to the class’s role in the application.

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

9. How can you test a Spring Boot application?

To test a Spring Boot application, use the Spring Boot Test module, which provides test support and utilities, such as @SpringBootTest, @WebMvcTest, @DataJpaTest, and @MockBean annotations. Write test classes using your preferred testing framework (e.g., JUnit, TestNG) and use Spring Boot’s testing annotations to configure the test context, load specific configurations, or isolate specific layers of your application.

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

10. What is the purpose of the @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping annotations in Spring Boot?

These annotations are shorthand versions of the @RequestMapping annotation, specifically designed for each HTTP method (GET, POST, PUT, and DELETE). They are used to define request mappings for controller methods, associating them with specific HTTP methods and paths.

Here are some benefits of using these annotations:

  • These annotations help improve the readability and conciseness of your code by providing specific annotations for common HTTP methods.
  • They make it clear which HTTP method a particular method in your controller is designed to handle, enhancing the expressiveness of your API.
  • The annotations also allow you to use additional attributes specific to the HTTP method, such as consumes and produces, without the need for the more generic @RequestMapping.

Now let’s go over of each of the HTTP annotations:

@GetMapping

The @GetMapping annotation is used to handle HTTP GET requests. It is a shortcut for @RequestMapping(method = RequestMethod.GET).

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

    @GetMapping("/resource")
    public String getResource() {
        // Handle GET request
        return "This is a GET resource.";
    }
}

@PostMapping

The @PostMapping annotation is used to handle HTTP POST requests. It is a shortcut for @RequestMapping(method = RequestMethod.POST).

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

    @PostMapping("/resource")
    public String createResource(@RequestBody Resource resource) {
        // Handle POST request
        return "Resource created.";
    }
}

@PutMapping

The @PutMapping annotation is used to handle HTTP PUT requests. It is a shortcut for @RequestMapping(method = RequestMethod.PUT).

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

    @PutMapping("/resource/{id}")
    public String updateResource(@PathVariable Long id, @RequestBody Resource resource) {
        // Handle PUT request
        return "Resource updated.";
    }
}

@DeleteMapping

The @DeleteMapping annotation is used to handle HTTP DELETE requests. It is a shortcut for @RequestMapping(method = RequestMethod.DELETE).

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

    @DeleteMapping("/resource/{id}")
    public String deleteResource(@PathVariable Long id) {
        // Handle DELETE request
        return "Resource deleted.";
    }
}

Reference: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-requestmapping

12. What is the difference between Spring Boot and Spring MVC?

Spring Boot and Spring MVC are related but distinct frameworks:

  • Spring Boot: A framework that simplifies the configuration and deployment of Spring applications by providing pre-configured templates (starters), auto-configuration, an embedded server, and other features to streamline development.
  • Spring MVC: A module within the Spring Framework that provides a web application framework, including features like request handling, data binding, and view resolution. Spring Boot builds upon Spring MVC to offer a more streamlined development experience.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-using-the-default-package

13. How can you create a custom starter in Spring Boot?

To create a custom starter in Spring Boot, follow these steps:

  1. Create a new project with a descriptive name (e.g., my-starter).
  2. Add the required dependencies for your starter.
  3. Implement the auto-configuration classes and use the @Configuration and @Conditional annotations to define the conditions under which your configuration should be applied.
  4. Create a spring.factories file in the src/main/resources/META-INF directory and reference your auto-configuration classes.
  5. Package your starter as a library and include it as a dependency in your target projects.

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

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

The @Lazy annotation is used to indicate that a bean should be lazily initialized, meaning that it will only be created and initialized when it is first requested or used, rather than during the application context’s startup phase. This can help improve the startup performance of your application.

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

15. How can you configure CORS in Spring Boot?

To configure CORS (Cross-Origin Resource Sharing) in Spring Boot, use the @CrossOrigin annotation on your controller methods or classes, or configure a CorsRegistry bean in a WebMvcConfigurer implementation to define global CORS policies.

Reference: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-cors

16. How can you deploy a Spring Boot application to an external application server?

To deploy a Spring Boot application to an external application server, configure your project to generate a WAR file instead of a JAR file. In your pom.xml or build.gradle file, change the packaging type to war and configure the embedded server dependencies as provided. Update your SpringApplication class to extend SpringBootServletInitializer. Finally, build your application and deploy the resulting WAR file to your application server.

1. Build the Deployable Artifact

Use the following Maven or Gradle commands to build the deployable artifact (JAR or WAR):

For Maven:

Bash
mvn clean package

This command generates a JAR file in the target directory.

For Gradle:

Bash
./gradlew clean build

This command generates a JAR file in the build/libs directory.

2. Package as a WAR file (Optional)

If you want to deploy your Spring Boot application as a traditional WAR file (e.g., for deployment in a standalone servlet container like Apache Tomcat), you can modify your pom.xml (for Maven) or build.gradle (for Gradle) to produce a WAR file instead of a JAR file.

For Maven:

XML
<packaging>war</packaging>

This command generates a JAR file in the target directory.

For Gradle:

Groovy
apply plugin: 'war'
3. Configure External Application Server
  1. Jetty: Copy the generated JAR or WAR file to the webapps directory or deploy it by configuring Jetty to use an external deployment descriptor.
  2. Tomcat: Copy the generated JAR or WAR file to the webapps directory. Alternatively, configure Tomcat to deploy your application by copying the file to the deploy directory.
  3. WildFly: Deploy your application using the WildFly Management Console or by copying the JAR or WAR file to the deployments directory.

After copying the jar (or war file, start ther application server and open the application url to access it.

Reference: Spring Boot – Deployable war file

17. What is a Spring Boot Starter and how does it work?

A Spring Boot starter is a pre-configured template that simplifies the process of adding dependencies and setting up configurations for your Spring Boot application. Starters provide a set of dependencies tailored for a specific use case or technology, allowing you to quickly set up your project without manually adding and managing each individual dependency.

Starters work by using the concept of auto-configuration. When you include a starter in your project, Spring Boot will automatically configure your application based on the dependencies present in the classpath. This enables you to quickly start building your application without spending time on boilerplate configuration.

Reference: Spring Boot Starter

18. How can you secure a Spring Boot application?

To secure a Spring Boot application, use the Spring Security framework by adding the spring-boot-starter-security dependency to your project. Spring Security provides features like authentication, authorization, CSRF protection, and other security features. Configure Spring Security using the @EnableWebSecurity annotation and extend the WebSecurityConfigurerAdapter class to customize your security settings.

Here is an example on securing access to web pages or web services.

1. Add Spring Security Dependency

In your pom.xml (for Maven) or build.gradle (for Gradle), add the Spring Security dependency:

For Maven:

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

For Gradle:

Groovy
implementation 'org.springframework.boot:spring-boot-starter-security'
2. Configure Security in application.propertiesapplication.yml

By default, Spring Security enables basic authentication and generates a random password during application startup. You can customize this behavior by providing your own credentials:

Plaintext
spring.security.user.name=user
spring.security.user.password=password
3. Customize Security Configuration

Create a class that extends WebSecurityConfigurerAdapter to customize the security configuration:

Groovy
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

In this example, /login is the custom login page, and access to other pages requires authentication. The PasswordEncoder bean is used to encode passwords.

4. Customize User Authentication

You can customize user authentication by providing your own UserDetailsService and AuthenticationProvider. Here’s an example using in-memory authentication:

Java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user")
                .password(passwordEncoder().encode("password"))
                .roles("USER");
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user = User.builder()
            .username("user")
            .password(passwordEncoder().encode("password"))
            .roles("USER")
            .build();
        
        return new InMemoryUserDetailsManager(user);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Note: Use HTTPS. Always enfore HTTPS to ensure secure communication. Refer to earlier question on configuring HTTPS.

Reference: Spring Boot Security

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

To create a scheduled task in Spring Boot, use the @Scheduled annotation on a method and configure a fixed rate, fixed delay, or cron expression for the task. Enable scheduling in your application by adding the @EnableScheduling annotation to a configuration class.

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

20. What is the purpose of the @EnableAutoConfiguration annotation in Spring Boot?

The @EnableAutoConfiguration annotation is used to enable Spring Boot’s auto-configuration feature, which automatically configures your application based on the dependencies present in the classpath. This annotation is typically used in your SpringApplication class and is included by default when you use the @SpringBootApplication annotation.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-auto-configuration

21. What is a CommandLineRunner in Spring Boot, and how can you use it?

A CommandLineRunner is an interface in Spring Boot that allows you to execute code at the startup of your application. To use a CommandLineRunner, create a bean that implements the interface and define the run method with the code you want to execute. Spring Boot will automatically call the run method of all CommandLineRunner beans during the startup process.

Create a CommandLineRunner Bean:
Java
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 custom initialization logic goes here
        System.out.println("Command Line Runner executed!");
    }
}

In the code above, I annotated MyCommandLineRunner with @Component to indicate that it should be picked up by Spring’s component scanning. The run method contains the code that will be executed once the application starts.

Reference: Command line runner

22. How can you enable HTTPS in a Spring Boot application?

To enable HTTPS in a Spring Boot application, follow these steps:

  1. Obtain an SSL certificate (e.g., self-signed or from a certificate authority).
  2. Convert the certificate into a Java KeyStore (JKS) or PKCS12 format.
  3. Configure the server.ssl.* properties in your application.properties or application.yml file, specifying the keystore location, password, and other relevant settings.
  4. Set the server.port property to 443 or another secure port for HTTPS traffic.
1. Generate Self-Signed Certificate for Development or Testing:

Use the keytool, included with JDK to generate a self-signed certificate:

Bash
keytool -genkeypair -alias myapp -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650
2. Configure Spring Boot to Use HTTPD:

You can configure HTTPS in your Spring Boot application by specifying the keystore properties in the application.properties or application.yml file.

server.port=8443
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=password
server.ssl.key-store-type=PKCS12
server.ssl.key-alias=myapp
  • server.port: The port on which the application should run.
  • server.ssl.key-store: The path to the keystore file.
  • server.ssl.key-store-password: The password for the keystore.
  • server.ssl.key-store-type: The type of keystore.
  • server.ssl.key-alias: The alias for the key in the keystore.
3. Redirect HTTP to HTTPS:

If you want to enforce HTTPS and redirect all HTTP requests to HTTPS, you can configure this in your SecurityConfiguration or main application class:

Java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/", "https://localhost:8443");
    }
}

This configuration redirects all requests from http://localhost:8080 to https://localhost:8443.

Reference: How to configure webserver SSL in Spring Boot

23. What is the purpose of the @ExceptionHandler annotation in Spring Boot?

The @ExceptionHandler annotation is used in controller classes to define methods that handle specific exceptions thrown by other methods within the same controller. This allows you to centralize exception handling and customize the response returned to the client when an exception occurs.

Reference: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-exceptionhandler

24. What is a SpringApplication class in Spring Boot, and what is its purpose?

A SpringApplication class is the entry point of a Spring Boot application. It typically contains a main method that initializes the SpringApplication and starts the embedded server. The SpringApplication class is also responsible for applying default configurations, scanning for components, and initializing the application context.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-structuring-your-code

25: What is the purpose of the @Repository annotation in Spring Boot?

The @Repository annotation is used to define a repository or data access layer class, indicating that the class is responsible for interacting with a data store, such as a database or an external API. It is a specialized version of the @Component annotation, providing semantic meaning to the class’s role in the application.

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;
    }

}

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

Conclusion

Hopefully you found these questions helpful to help you prepare for a Java and Spring Boot interview. By familiarizing yourself with these concepts and techniques, you are now better prepared for success in your interview for a new position as a Spring Boot programmer.