Spring Boot Interview Questions (7+)

What is embedded container in spring boot and why it is important?

Spring boot comes with an embedded container which is a light weight server that can run inside spring boot application. It eliminates the Burdon from developer of packaging the application and deploying it in an external heavyweight server like tomcat or jetty.

This embedded container also support hot reloading that means we don't have to restart the application when ever we make any changes it automatically redeploys the application whenever there is a change.

How to enable hot reloading in spring boot ?

its very simple, just add below dependency and enable "build project automatically" setting in your editor.

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

How Can you externalize your application configuration properties ?

  • application.propertiesor application.yml Files: Spring Boot automatically loads configuration properties from application.properties or application.yml files located in the classpath. You can define your properties directly in these files.

  • Profile-specific Properties: You can have separate configuration files for different environments or profiles. For example, you can have application-dev.properties for development, application-prod.properties for production, etc. Spring Boot automatically picks up the properties based on the active profile.

    Activate Profiles: By default, Spring Boot uses the default profile. You can activate different profiles by setting the spring.profiles.active property in application.properties or by passing it as a command-line argument.

    in application.properties : spring.profiles.active=dev

    Or

    java -jar my-spring-boot-app.jar --spring.profiles.active=prod

  • Command-Line Arguments: You can override properties from the command line by specifying them using the -D option. For example:

    https://www.baeldung.com/spring-boot-command-line-arguments

  • Environment Variables: You can also use environment variables to set configuration properties. Spring Boot automatically converts environment variables to configuration properties.

  • External Configuration Files: Spring Boot allows you to specify an external configuration file location using the spring.config.location property. For example:

    java -jar myapp.jar --spring.config.location=/path/to/config.properties

What Spring Boot features help develop Microservices Applications?

Spring Boot offers several features that helps with the development of microservices applications:

  1. Spring Boot Starter: Spring Boot provides a collection of starter dependencies that simplify the setup of various components, such as Spring Data, Spring Security, and Spring Cloud, which are commonly used in microservices architecture.

  2. Embedded Servers: Spring Boot comes with embedded servers like Tomcat, Jetty, and Undertow, allowing you to package your application as an executable JAR file with an embedded server, simplifying deployment and scaling.

  3. Autoconfiguration: Spring Boot's autoconfiguration feature automatically configures your application based on the dependencies you've added to your project. This reduces the need for manual configuration and boilerplate code, making it easier to set up microservices.

  4. Actuator: Spring Boot Actuator provides monitoring and management endpoints that allow you to monitor your application's health, metrics, and other useful information. This is essential for managing and monitoring microservices in production.

  5. Spring Cloud: Spring Cloud provides tools for building microservices architecture, such as service discovery (with Netflix Eureka or HashiCorp Consul), client-side load balancing (with Ribbon), distributed configuration management (with Spring Cloud Config), and circuit breakers (with Netflix Hystrix or Resilience4j).

  6. Spring Data: Spring Data simplifies the implementation of data access layers by providing a consistent, easy-to-use programming model for accessing data from various sources, such as relational databases, NoSQL databases, and cloud storage services.

  7. Spring Boot DevTools: Spring Boot DevTools provides features like automatic restarts and live reloading, which can significantly improve developer productivity during the development of microservices applications.

What are the Spring Boot Annotations?

Below are the most common annotations of spring boot.

  1. @SpringBootApplication: This annotation is used to mark the main class of a Spring Boot application. It combines three other annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan. It essentially tells Spring Boot to start auto-configuration and component scanning from the package where this annotation is declared.

  2. @Configuration: This annotation is used to specify that a class declares one or more bean definitions and can be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.

  3. @EnableAutoConfiguration: This annotation tells Spring Boot to automatically configure the application based on its dependencies and the content of the classpath.

  4. @ComponentScan: This annotation is used in Spring Boot applications to specify the base packages to scan for Spring-managed components such as controllers, services, repositories, and other annotated classes. It tells Spring where to look for components that need to be instantiated and managed by the Spring container.

  5. @RestController: This annotation is used to define RESTful web services. It combines @Controller and @ResponseBody annotations, indicating that the return value of the methods should be directly written to the HTTP response body.

  6. @RequestMapping: This annotation is used to map web requests to specific handler methods in Spring MVC controllers. It can be applied at the class level or method level to define the URL mappings.

  7. @Autowired: This annotation is used for automatic dependency injection. It allows Spring to automatically resolve and inject the beans into the dependent objects.

  8. @Component: This annotation marks a Java class as a Spring component, allowing it to be automatically detected and registered as a bean in the Spring application context.

  9. @Service: This annotation is used to mark a class as a service component in the Spring application context. It is typically used to define business logic or transactional operations.

  10. @Repository: This annotation is used to mark a class as a repository component in the Spring application context. It is typically used to define data access operations.

  11. @ConditionalOnProperty: This annotation is used to conditionally enable or disable a bean or configuration based on the presence or absence of a specified property in the environment.

What annotations are used to create Interceptors in spring boot?

In Spring Boot, you typically use aspects and interceptors for cross-cutting concerns such as logging, security, and transaction management. Spring Boot leverages Spring's AOP (Aspect-Oriented Programming) capabilities and provides annotations to create interceptors.

The primary annotations used to create interceptors in Spring Boot are:

  1. @Aspect: This annotation is used at the class level to mark a class as an aspect.

  2. JoinPoint annotations: These annotations specify the pointcuts where the interceptor methods will be executed. Common JoinPoint annotations include:

    • @Before: Executes advice before the method execution.

    • @After: Executes advice after the method returns successfully.

    • @Around: Executes advice around the method invocation, allowing manipulation of the method execution.

    • @AfterReturning: Executes advice after the method returns a result.

    • @AfterThrowing: Executes advice after the method throws an exception.

Below code explains interceptors in spring boot using spring AOP annotations

  1. Imports:

     import org.aspectj.lang.JoinPoint;
     import org.aspectj.lang.ProceedingJoinPoint;
     import org.aspectj.lang.annotation.*;
     import org.springframework.stereotype.Component;
    

    These are necessary imports for using Spring's AOP features and annotations.

  2. Aspect Class Declaration:

     @Aspect
     @Component
     public class LoggingInterceptor {
    
    • @Aspect: Indicates that this class is an aspect.

    • @Component: Marks the class as a Spring-managed component, allowing it to be automatically scanned and instantiated.

  3. @Before Advice:

     @Before("execution(* com.example.service.*.*(..))")
     public void logBeforeServiceMethods(JoinPoint joinPoint) {
         System.out.println("Logging before executing service method: " + joinPoint.getSignature().getName());
     }
    
    • @Before: Specifies that the method should be executed before the execution of methods matched by the specified pointcut expression.

    • execution(* com.example.service.*.*(..)): This is a pointcut expression that matches all methods within the com.example.service package.

    • JoinPoint: Provides metadata about the intercepted method, such as method signature.

  4. @After Advice:

     @After("execution(* com.example.service.*.*(..))")
     public void logAfterServiceMethods(JoinPoint joinPoint) {
         System.out.println("Logging after executing service method: " + joinPoint.getSignature().getName());
     }
    
    • @After: Indicates that the method should be executed after the method execution.
  5. @Around Advice:

     @Around("execution(* com.example.service.*.*(..))")
     public Object logAroundServiceMethods(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
         System.out.println("Logging around executing service method: " + proceedingJoinPoint.getSignature().getName());
         Object result = proceedingJoinPoint.proceed();
         System.out.println("Logging after completion of service method: " + proceedingJoinPoint.getSignature().getName());
         return result;
     }
    
    • @Around: Executes advice around the method invocation, allowing control over the method execution.
  6. @AfterReturning Advice:

     @AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result")
     public void logAfterReturningServiceMethods(JoinPoint joinPoint, Object result) {
         System.out.println("Logging after returning from service method: " + joinPoint.getSignature().getName() + ", Result: " + result);
     }
    
    • @AfterReturning: Executes advice after the method successfully returns a result.
  7. @AfterThrowing Advice:

     @AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "exception")
     public void logAfterThrowingServiceMethods(JoinPoint joinPoint, Exception exception) {
         System.out.println("Logging after throwing from service method: " + joinPoint.getSignature().getName() + ", Exception: " + exception.getMessage());
     }
    
    • @AfterThrowing: Executes advice after the method throws an exception.

In summary, this aspect intercepts method executions within the com.example.service package and logs messages before, after, around method execution, after returning from the method, and after an exception is thrown from the method.

Did you find this article valuable?

Support Java Blogs By Hemant by becoming a sponsor. Any amount is appreciated!