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

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 secure Actuator endpoints in Spring Boot?

You can secure Actuator endpoints using Spring Security by adding the spring-boot-starter-security dependency and configuring security settings, such as authentication and authorization, for the Actuator endpoints.

Below is an example of how to secure Actuator endpoints with basic authentication. This example uses HTTP Basic Authentication, and it assumes you already have Spring Security configured in your project.

Add the spring-boot-starter-security dependency to your project:

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

Configure Spring Security to secure Actuator endpoints in your application.properties or application.yml:

Plaintext
# Enable security for all endpoints
management.endpoints.web.exposure.include=*

# Configure security roles for different endpoints
management.endpoint.health.roles=ACTUATOR_ADMIN
management.endpoint.info.roles=ACTUATOR_ADMIN
# Add more endpoints and roles as needed

Create a security configuration class to specify security rules:

Java
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/actuator/**").hasRole("ACTUATOR_ADMIN")
                .anyRequest().authenticated()
                .and()
            .httpBasic();
    }
}

In this example, the security configuration ensures that access to any endpoint under /actuator/** requires the role ACTUATOR_ADMIN. You can customize the roles and endpoints based on your specific requirements.

Reference: Spring Boot Actuator – Security

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

The @Async annotation is used to execute a method asynchronously in a separate thread. It helps in improving the performance and responsiveness of your application by offloading time-consuming tasks to background threads.

Reference: Spring Framework – 35.3.3. Using the @Async annotation

3. How can you enable asynchronous processing in Spring Boot?

To enable asynchronous processing in Spring Boot, add the @EnableAsync annotation to a configuration class. This enables the detection of the @Async annotation and creates a default task executor for asynchronous method execution.

In the example below, when someMethod is called, it will invoke performAsyncTask asynchronously in a separate thread.

1. Add the @EnableAsync annotation to your configuration class or main application class.

Java
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

@Configuration
@EnableAsync
public class AsyncConfig {
    // Other configurations can be added here
}

The @EnableAsync annotation enables Spring’s asynchronous processing capabilities.

2. Use @Async annotation on methods that should be executed asynchronously.

Java
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Async
    public void performAsyncTask() {
        // Asynchronous task logic
        System.out.println("Async task is being executed in a separate thread.");
    }
}

The @Async annotation on a method indicates that it should be executed asynchronously.

3. Invoke the asynchronous method from your code.

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

@Component
public class MyComponent {

    private final MyService myService;

    @Autowired
    public MyComponent(MyService myService) {
        this.myService = myService;
    }

    public void someMethod() {
        // Invoke the asynchronous method
        myService.performAsyncTask();

        // Continue with other logic
        System.out.println("Continuing with other logic.");
    }
}

Reference: Spring Framework – 35.3.3. Using the @Async annotation

4. What is the purpose of the @Scheduled annotation in Spring Boot?

The @Scheduled annotation is used to define a method that should be executed periodically according to a fixed schedule, such as a fixed rate or a cron expression. It simplifies the creation of scheduled tasks in your application.

To use @Scheduled in Spring Boot, you can schedule methods to run at fixed intervals or at specific times.

Here’s a simple example:

1. Create a Spring Boot Application:

Java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

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

The @EnableScheduling annotation enables scheduling in your application.

2. Create a Service with a Scheduled Method:

Java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class MyScheduledService {

    @Scheduled(fixedRate = 5000) // Run every 5 seconds
    public void scheduledTask() {
        System.out.println("Scheduled task executed at fixed rate");
    }

    @Scheduled(cron = "0 0 0 * * ?") // Run every day at midnight
    public void dailyTask() {
        System.out.println("Daily task executed");
    }
}

In this example, scheduledTask is scheduled to run every 5 seconds (fixedRate), and dailyTask is scheduled to run every day at midnight (cron expression).

When you run the application, you should see the scheduled tasks executing based on the specified intervals.

Reference: Spring Framework – 35.2.3. Using the @Scheduled annotation

5. How can you use Spring Boot with a SQL database?

To use Spring Boot with a SQL database, add the appropriate spring-boot-starter-data-* dependency (e.g., spring-boot-starter-data-jpa for JPA, spring-boot-starter-data-jdbc for JDBC) and configure the database connection properties in the application.properties or application.yml file.

To use a SQL database with Spring Boot, you can leverage Spring Data JPA for easy integration. Below is a simple example of how to set up a Spring Boot application with Spring Data JPA to interact with an H2 in-memory database.

Add Dependencies:Add the necessary dependencies in your pom.xml file (if using Maven) or build.gradle file (if using Gradle).

For Maven:

XML
<!-- Spring Boot Starter Data JPA -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- H2 Database -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

For Gradle:

Groovy
// Spring Boot Starter Data JPA
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

// H2 Database
runtimeOnly 'com.h2database:h2'

2. Configure Database Connection: In your application.properties or application.yml file, configure the database connection properties:

Plaintext
# H2 Database Configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password

# Hibernate Configuration
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

3. Create Entity: Define a simple entity class representing a table in your database. For example:

Java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;
    private String email;

    // Constructors, getters, setters...
}

4. Create Repository Interface: Create a repository interface by extending JpaRepository. Spring Data JPA will automatically generate basic CRUD methods based on the entity type:

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

public interface UserRepository extends JpaRepository<User, Long> {
    // Custom query methods can be added here
}

5. Use Repository in Service or Controller: You can now use the UserRepository in your service or controller to perform database operations.

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

@Service
public class UserService {

    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public Iterable<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User createUser(User user) {
        return userRepository.save(user);
    }

    // Other methods as needed...
}

Reference: Spring Data JPA – Reference Documentation

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

The @EnableAutoConfiguration annotation enables Spring Boot’s auto-configuration feature, which automatically configures your application based on the dependencies present in the classpath, environment settings, and configuration files.

When you use @SpringBootApplication, it already includes @EnableAutoConfiguration. However, if you want to use @EnableAutoConfiguration separately, you can do so as follows:

1. Add the Dependency: Make sure you have the Spring Boot Starter in your project.

For Maven:

XML
<!-- Spring Boot Starter -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

For Gradle:

Plaintext
// Spring Boot Starter
implementation 'org.springframework.boot:spring-boot-starter'

2. Use @EnableAutoConfiguration: Create a simple Spring Boot application class and use @EnableAutoConfiguration:

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

@EnableAutoConfiguration
public class MySpringBootApplication {

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

Alternatively, you can use @SpringBootApplication which includes @EnableAutoConfiguration:

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

@EnableAutoConfiguration
public class MySpringBootApplication {

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

When using @SpringBootApplication, it not only includes @EnableAutoConfiguration but also includes @ComponentScan and @Configuration, making it a convenient and common choice for starting a Spring Boot application. The @SpringBootApplication annotation is often used for stand-alone Spring Boot applications.

Reference: Spring Boot Auto-Configuration

7. What is a SpringBootApplication class in Spring Boot?

In Spring Boot, the @SpringBootApplication annotation is commonly used to denote the main class of a Spring Boot application, and it implicitly includes the @EnableAutoConfiguration, @ComponentScan, and @Configuration annotations. The @SpringBootApplication annotation is often used in conjunction with the SpringApplication.run() method.

Here’s an example:

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

@SpringBootApplication
public class MySpringBootApplication {

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

In this example, the MySpringBootApplication class is annotated with @SpringBootApplication, and the main method uses SpringApplication.run() to launch the Spring Boot application.

The @SpringBootApplication annotation is a composite annotation that combines several annotations:

  • @EnableAutoConfiguration: Enables Spring Boot’s auto-configuration feature.
  • @ComponentScan: Enables component scanning to discover and register beans in the application context.
  • @Configuration: Marks the class as a configuration class, allowing it to define beans.

Reference:

8. How to Use ApplicationRunner Interface to run code after Context Initialization?

If you want to customize the behavior of the SpringApplication, you can use the @SpringBootApplication annotation along with a class that implements the CommandLineRunner interface or the ApplicationRunner interface. These interfaces provide a way to run code after the application context has been initialized.

In this example, the MySpringBootApplication class implements the ApplicationRunner interface, and the run method contains your custom initialization code. This code will be executed after the application context has been initialized.

Java
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MySpringBootApplication implements ApplicationRunner {

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

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // Your custom initialization code goes here
        System.out.println("Application started!");
    }
}

Reference: Running code on startup in Spring Boot

9. What are the benefits of using an embedded server in Spring Boot?

Using an embedded server in Spring Boot offers several benefits, such as:

  • Simplified deployment: The application can be run as a standalone JAR or WAR file, without requiring an external application server.
  • Consistent development and production environments: The same server and configurations can be used in both environments, reducing the risk of environment-specific issues.
  • Faster startup and shutdown times: The embedded server starts and stops along with the application, making it faster and more efficient than an external application server.

You can include a web server (such as Tomcat, Jetty, or Undertow) in the application itself. Below is an example of using the embedded Tomcat server in a Spring Boot application:

Configure Embedded Server Properties in your application.properties or application.yml file. For example, to configure Tomcat with a custom port, you can add the following to application.properties:

Plaintext
# Configure Tomcat server port
server.port=8080

Create a Spring Boot application with the main class with @SpringBootApplication annotation:

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

@SpringBootApplication
public class MySpringBootApplication {

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

When you run the application, Spring Boot will use the embedded Tomcat server. You’ll see output similar to the following indicating that Tomcat is starting:

Plaintext
Tomcat initialized with port(s): 8080 (http)

Reference: Spring Boot Embedded Servers

10. How do I change the default embedded server in spring boot?

The choice of an embedded server is a matter of preference or specific requirements. Spring Boot allows you to easily switch between embedded servers by changing the project’s dependencies.

For example, if you want to use Jetty instead of Tomcat, you can add the Jetty dependency in your pom.xml or build.gradle file:

For Maven:

XML
<!-- Jetty Embedded Server -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

For Gradle:

Plaintext
// Jetty Embedded Server
implementation 'org.springframework.boot:spring-boot-starter-jetty'

You can run your Spring Boot application, and it will use Jetty as the embedded server. The same approach can be used for other embedded servers supported by Spring Boot, such as Undertow.

Reference: Spring Boot Embedded Servers

11. What is the Spring Boot Admin?

Spring Boot Admin is a third-party library that provides a web-based user interface for managing and monitoring Spring Boot applications. It simplifies the visualization of application metrics, health, and configuration by aggregating data from Actuator endpoints.

Shown below is example of how you can set up Spring Boot Admin in a Spring Boot application:

Add Dependencies:Add the Spring Boot Admin Starter dependency to your project. Include the following dependency in your pom.xml (if using Maven) or build.gradle (if using Gradle):

For Maven:

XML
<!-- Spring Boot Admin Starter -->
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-server</artifactId>
    <version>2.5.2</version> <!-- Use the latest version available -->
</dependency>

For Gradle:

Plaintext
// Spring Boot Admin Starter
implementation 'de.codecentric:spring-boot-admin-starter-server:2.5.2' // Use the latest version available

Configure Spring Boot Admin:

Create a configuration class to enable the Spring Boot Admin server and specify the context path:

Java
import de.codecentric.boot.admin.server.config.EnableAdminServer;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAdminServer
public class SpringBootAdminConfig {
    // Additional configuration if needed
}

Run the Application:

Run your Spring Boot application, and the Spring Boot Admin server will be accessible at http://localhost:8080/admin. You can view and manage registered Spring Boot applications from this dashboard.

Reference: Spring Boot Admin

12. What is the difference between @RestController and @Controller annotations in Spring Boot?

Both @Controller and @RestController annotations are used to define controller classes in Spring Boot, but with different purposes and use cases.

@Controller Example

A general-purpose annotation for defining controller classes that can return views or response bodies, depending on the use of the @ResponseBody annotation.

Controllers annotated with @Controller are typically used when you want to create web pages and return HTML views. They are part of the traditional Spring MVC approach, where the controller methods return the names of views to be resolved by the view resolver.

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

@Controller
public class MyController {

    @GetMapping("/hello")
    public String hello() {
        return "hello"; // Returns the view name (e.g., hello.jsp or hello.html)
    }
}

@RestController

A specialized version of @Controller that assumes all methods return the response body directly, without the need for a @ResponseBody annotation. It is commonly used for RESTful web services.

Controllers annotated with @RestController are used to build RESTful APIs that return data in a format like JSON or XML directly to the client. The return value of the methods is serialized directly into the response body.

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

@RestController
public class MyRestController {

    @GetMapping("/api/hello")
    public String hello() {
        return "Hello, World!"; // Returns the string directly in the response body
    }
}

Reference: MVC Controller

13. How can you handle exceptions in Spring Boot?

In Spring Boot, you can handle exceptions using the following techniques:

  • Using @ExceptionHandler methods within a controller class
  • Implementing a @ControllerAdvice or RestControllerAdvice class with @ExceptionHandler methods
  • Customizing the default error handling by extending ResponseEntityExceptionHandler.

Shown below is an example on how you can use a custom exception handler to deal with RuntimeExceptions.

Create a custom exception that extends RuntimeException or any other appropriate exception class:

Java
public class CustomNotFoundException extends RuntimeException {
    public CustomNotFoundException(String message) {
        super(message);
    }
}

Now create a global exception handler class using @ControllerAdvice and @ExceptionHandler:

Java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomNotFoundException.class)
    public ResponseEntity<String> handleNotFoundException(CustomNotFoundException ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
    }

    // Add more exception handlers as needed
}

In this example, if a CustomNotFoundException is thrown, the handleNotFoundException method will be invoked, and it will return a 404 Not Found response with the exception message.

Finally, add some code to throw an exception to test your custom exception handler:

Java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

    @GetMapping("/user/{id}")
    public String getUserById(@PathVariable Long id) {
        // Simulate a scenario where the user is not found
        if (id == 1) {
            throw new CustomNotFoundException("User not found with id: " + id);
        }
        return "User found!";
    }
}

Reference: Exception Handling

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

The @Repository annotation is used to define a data access layer class, such as a DAO (Data Access Object) or a Spring Data repository. It is a specialized version of the @Component annotation, indicating that the class is responsible for database operations.

Here is an example:

Create and Entity:

Java
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class User {

    @Id
    private Long id;

    private String username;
    private String email;

    // Constructors, getters, setters...
}

Create a @Repository Interface bye extending JpaRepository (or another JPA repository interface):

Java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    // You can define additional query methods here if needed
}

Note the use of @Repository here. While it’s not strictly necessary to use it when working with Spring Data repositories, it’s always good practice to use @Repository annotation to indicate that this interface is a repository and benefits from Spring’s data access exception translation.

Now you can use the UserRepository class in a service or controller to perform data access operations:

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

@Service
public class UserService {

    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User getUserById(Long userId) {
        return userRepository.findById(userId).orElse(null);
    }

    // Other methods as needed...
}

Reference: Spring Data Repositories

15. How can you implement validation in Spring Boot?

To implement validation in Spring Boot, use the Bean Validation API (e.g., Hibernate Validator) by adding the spring-boot-starter-validation dependency, annotating your domain classes with validation constraints (e.g., @NotNull, @Size), and adding the @Valid annotation to the method parameters in your controller.

1. Add Data Validation To Your Model Class:

Java
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;

public class User {

    @NotEmpty(message = "Username cannot be empty")
    @Size(min = 3, max = 50, message = "Username must be between 3 and 50 characters")
    private String username;

    @NotEmpty(message = "Email cannot be empty")
    @Email(message = "Invalid email format")
    private String email;

    // Constructors, getters, setters...
}

2. Use @Valid in Controller Methods to trigger validation:

Java
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@Validated
public class UserController {

    @PostMapping("/users")
    public ResponseEntity<String> createUser(@Valid @RequestBody User user) {
        // Process the user if validation passes
        return ResponseEntity.ok("User created successfully");
    }
}

The @Validated annotation is used at the class level, and the @Valid annotation is used on the method parameter. This ensures that the User object passed in the request body is validated before the method is executed.

Reference:

  1. Bean Validation
  2. Spring Boot Data Validation

16. How can you create a custom endpoint in Actuator?

To create a custom endpoint in Actuator, create a class that implements the Endpoint interface or extends the AbstractEndpoint class, define the behavior of the endpoint in the invoke() method, and register the endpoint as a bean in your configuration.

1. Create a custom endpoint:

In the example below, I will create a simple custom endpoint that returns custom information. I will do so by creating a CustomEndpoint class with a method that uses the @ReadOperation annotation.

The @ReadOperation annotated method will be invoked when the endpoint is accessed.

Java
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;

@Endpoint(id = "custom")
public class CustomEndpoint {

    @ReadOperation
    public String getCustomInfo() {
        return "Custom Endpoint: It works!";
    }
}

Now, I will register the CustomEndpoint in a configuration class.

Java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CustomEndpointConfig {

    @Bean
    public CustomEndpoint customEndpoint() {
        return new CustomEndpoint();
    }
}

You can access the custom endpoint either in a browser or a shell. Below is an example using the curl command.

Bash
curl http://localhost:8080/actuator/custom

The server will respond with a JSON message:

JSON
"Custom Endpoint: It works!"

Reference: Spring Boot Actuator – Custom Endpoints

17. What is the purpose of the @Profile annotation in Spring Boot?

The @Profile annotation is used to define beans or configurations that should only be active for specific profiles. Profiles are a way to silo parts of your application configuration and make it available only in certain environments (e.g., development, production).

1. Create Configuration Classes for Different Profiles:

First, I will create a profile to use in a development profile:

Java
// Development Profile Configuration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
@Profile("development")
public class DevelopmentConfig {

    @Bean
    public String environmentName() {
        return "Development Environment";
    }
}

Second, I will create a profile to use in a production profile:

Java
// Production Profile Configuration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
@Profile("production")
public class ProductionConfig {

    @Bean
    public String environmentName() {
        return "Production Environment";
    }
}

2. Using the Configurations in a Service:

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

@Service
public class MyService {

    private final String environmentName;

    @Autowired
    public MyService(String environmentName) {
        this.environmentName = environmentName;
    }

    public String getEnvironmentName() {
        return environmentName;
    }
}

3. Activate the appropriate profile

I will use the properties file for selecting the required profile.

Plaintext
spring.profiles.active=development

There are three distinct ways to activate a profile:

  • Command line: java -jar app.jar --spring.profiles.active=development
  • application .properties: spring.profiles.active=development
  • Programmatically: SpringApplication.run(App.class, args, new String[]{"development"});

Reference: Spring Boot Profiles

18. What are three different ways to activate Application profiles in Spring Boot?

To create a custom banner for a Spring Boot application, create a banner.txt file with your desired banner text and place it in the src/main/resources directory. Spring Boot will automatically display this banner at startup.

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.setBannerMode(Banner.Mode.CONSOLE);
        app.run(args);
    }
}

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

19. How can you create a custom banner for a Spring Boot application?

To create a custom banner for a Spring Boot application, create a banner.txt file with your desired banner text and place it in the src/main/resources directory. Spring Boot will automatically display this banner at startup.

If you want to change the banner location then you need to set the path in the application.properties file:

Plaintext
spring.banner.location=classpath:/path/to/banner/bannerfile.txt

You can also customize additional properties related to banner visibility:

Plaintext
spring.banner.image.location=classpath:banner.gif

spring.banner.image.height= 
spring.banner.image.invert= 
spring.banner.image.margin= 
spring.banner.image.width=  

Reference: Spring Boot Features Banner

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

The @Order annotation is used to specify the order in which beans or components are processed or executed. It can be applied to various components, such as filters, listeners, or configurations, to define their execution order.

1. Create an interface for your components:

Java
public interface MyComponent {
    // Methods...
}

2. Create Multiple @Component classes:

Java
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(2)
public class ComponentA implements MyComponent {
    // Implementation...
}
Java
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class ComponentB implements MyComponent {
    // Implementation...
}

3. Use the Components:

I will now autowire the components where you need them, and they will be injected in the order defined by @Order.

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

@Service
public class MyService {

    private final List<MyComponent> components;

    @Autowired
    public MyService(List<MyComponent> components) {
        this.components = components;
    }

    // Access components in the order specified by @Order
}

Reference: Spring Bean Config Order

21. How can you serve static content in Spring Boot?

By default, Spring Boot serves static content from the src/main/resources/static, src/main/resources/public, src/main/resources/resources, and src/main/resources/META-INF/resources directories. You can also customize the static content location using the spring.resources.static-locations property.

Reference: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-spring-mvc-static-content

22. What is the purpose of the @Qualifier annotation in Spring Boot?

The @Qualifier annotation is used to resolve ambiguity when multiple beans of the same type are defined in the application context. It allows you to specify the bean name to be injected when using @Autowired or other injection mechanisms.

References

23. How can you perform a graceful shutdown in Spring Boot?

To perform a graceful shutdown in Spring Boot, enable the spring.lifecycle.timeout-per-shutdown-phase property and the server.shutdown property in the application.properties or application.yml file. This will allow the application to complete ongoing requests and close resources before shutting down.

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

24. How can you configure logging in Spring Boot?

In Spring Boot, you can configure logging by providing a logging configuration file, such as logback-spring.xml for Logback or log4j2-spring.xml for Log4j2, in the src/main/resources directory. You can also configure logging properties using the application.properties or application.yml file.

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

25. What is the purpose of the @PreAuthorize and @PostAuthorize annotations in Spring Boot?

The @PreAuthorize and @PostAuthorize annotations are used to define method-level security in Spring Boot, allowing you to specify access-control expressions that must be satisfied before or after a method is executed, respectively.

Reference: https://docs.spring.io/spring-security/site/docs/current/reference/html5/#prepost-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.