10 New Java-Spring-Boot Interview Questions for Developers series -23
Hello folks, In this article, I have published 10 more new Spring Boot interview questions with answers. Going forward, I will be posting more than 200+ interview questions exclusively on Spring Boot Microservice in a series of articles every week. Please stay tuned for more articles like these.
(A bit of context: I’ve conducted numerous interviews for software engineering positions in most of the MNCs. Additionally, there have been instances where I faced challenges during coding interviews due to lack of preparation.)
Are you preparing for a job interview as a Java developer?
Find my book Guide To Clear Java Developer Interview here Gumroad (PDF Format) and Amazon (Kindle eBook).
Guide To Clear Spring-Boot Microservice Interview here Gumroad (PDF Format) and Amazon (Kindle eBook).
Download the sample copy here: Guide To Clear Java Developer Interview[Free Sample Copy]
Guide To Clear Spring-Boot Microservice Interview[Free Sample Copy]
How will you use AOP in the spring-boot application?
To use Aspect-Oriented Programming (AOP) in a Spring Boot application, follow these steps:
Define an aspect: Create a class annotated with @Aspect that contains methods representing the cross-cutting concerns you want to apply. Inside these methods, define the logic to be executed at specific join points.
Configure AOP: In your Spring Boot configuration class, annotate it with @EnableAspectJAutoProxy to enable AOP functionality.
Define pointcuts: Use the @Pointcut annotation to define the specific join points in your codebase where the aspect will be applied. Pointcuts specify where the aspect’s advice (code to be executed) will be applied.
Implement advice: Annotate the methods in your aspect class with @Before, @After, @Around, or other advice annotations to specify the type of advice to be executed before, after, or around the join points.
Apply aspect to beans: Use the @Component or other stereotype annotations to mark your aspect class as a Spring bean. This allows Spring to recognize and apply the aspect to the target beans.
Run the application: Start your Spring Boot application, and the defined aspects will be applied to the target methods based on the configured pointcuts and advice.
How to implement the swagger endpoint in the spring boot?
To implement Swagger documentation in a Spring Boot application, follow these steps:
Add dependencies: Include the necessary dependencies in your project’s build file (build.gradle or pom.xml). The commonly used dependencies are springfox-swagger2 and springfox-swagger-ui.
Create a Swagger configuration class: Create a configuration class annotated with @Configuration or @EnableSwagger2. Configure the Swagger Docket bean, which defines the API documentation details.
What is Spring Batch processing? How do you implement it in spring-boot?
Spring Batch is a framework within the Spring ecosystem that provides support for batch processing of large volumes of data. It enables developers to build robust and scalable batch-processing applications.
To implement Spring Batch in a Spring Boot application:
- Add dependencies: Include the necessary dependencies in your project’s build file (build.gradle or pom.xml). The commonly used dependencies are spring-boot-starter-batch and spring-boot-starter-data-jpa.
- Define Jobs and Steps: Create job definitions by defining the steps involved in the batch processing. Each step specifies the necessary reader, processor, and writer components for the data processing task.
- Implement Reader, Processor, and Writer: Implement the necessary components for reading input data, processing it, and writing the results. Spring Batch provides various reader and writer implementations, such as JdbcCursorItemReader, ItemProcessor, JpaItemWriter, etc.
- Configure Batch Job: Create a configuration class for the Spring Batch job, typically annotated with @Configuration. Configure the job and its steps, including the reader, processor, and writer components. Use the @EnableBatchProcessing annotation to enable Spring Batch functionality.
- Execute the Job: Use the JobLauncher interface to start and execute the Spring Batch job. You can trigger the job programmatically or schedule it using a scheduler like Quartz or Spring Scheduler.
- Monitor and Handle Job Execution: Spring Batch provides features to monitor and handle job execution, such as job status, retrying failed steps, skip logic, and listeners. You can customize the behavior by implementing interfaces like ItemReadListener, ItemWriteListener, or extending the provided listener adapters.
How to implement pagination and sorting in Springboot?
Implementing pagination and sorting in a Spring Boot application typically involves handling the request parameters for page number, page size, sort field, and sort direction, and using them to retrieve the appropriate subset of data from a data source.
Here are the general steps to implement pagination and sorting in Spring Boot:
Define a repository interface: Create a repository interface that extends either JpaRepository or PagingAndSortingRepository provided by Spring Data JPA. This interface will provide the necessary methods for pagination and sorting.
public interface UserRepository extends JpaRepository<User, Long> {
}
Create a service class: Create a service class that encapsulates the business logic and interacts with the repository. Inject the repository into the service class.
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Page<User> getUsers(int pageNumber, int pageSize, String sortBy, String sortDirection) {
Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.by(Sort.Direction.fromString(sortDirection), sortBy));
return userRepository.findAll(pageable);
}
}
Create a controller: Create a REST controller that handles the HTTP requests and maps them to the appropriate service methods.
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public Page<User> getUsers(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "id") String sort,
@RequestParam(defaultValue = "asc") String direction) {
return userService.getUsers(page, size, sort, direction);
}
}
Test the pagination and sorting: Start the Spring Boot application and make a GET request to the /users endpoint with the appropriate query parameters for pagination and sorting.
GET /users?page=0&size=10&sort=name&direction=asc
This will retrieve the first page of users, with 10 users per page, sorted by the name field in ascending order.
How to implement exception handling in Springboot?
Implementing exception handling in a Spring Boot application involves defining custom exception classes, creating an exception handler, and configuring global exception handling.
Here are the general steps to implement exception handling in Spring Boot:
Define custom exception classes: Create custom exception classes that extend either RuntimeException or Exception to represent specific types of exceptions in your application.
public class CustomNotFoundException extends RuntimeException {
public CustomNotFoundException(String message) {
super(message);
}
}
public class CustomBadRequestException extends RuntimeException {
public CustomBadRequestException(String message) {
super(message);
}
}
Create an exception handler: Create an exception handler class that handles specific exceptions and returns an appropriate response to the client. The exception handler should be annotated with @ControllerAdvice and include methods annotated with @ExceptionHandler for handling specific exception types.
@ControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler(CustomNotFoundException.class)
public ResponseEntity<String> handleNotFoundException(CustomNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
@ExceptionHandler(CustomBadRequestException.class)
public ResponseEntity<String> handleBadRequestException(CustomBadRequestException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
}
// Add more exception handlers for other custom exceptions…
}
Configure global exception handling: Create a configuration class to enable global exception handling. This class should extend ResponseEntityExceptionHandler and override methods to handle specific types of exceptions. You can provide custom error messages or responses for these exceptions.
@Configuration
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status,
WebRequest request) {
// Handle validation errors and return a custom error response
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Validation error: " + ex.getMessage());
}
// Add more overridden methods to handle other types of exceptions…
}
Test exception handling: Trigger the exceptions in your application or send requests that would result in those exceptions being thrown. The exception handlers will catch these exceptions and return the appropriate response to the client.
How to implement interceptors in Springboot?
Implementing interceptors in a Spring Boot application allows you to intercept and process incoming requests and outgoing responses. Interceptors can be used for tasks such as logging, authentication, authorization, and modifying request/response headers.
Here are the general steps to implement interceptors in Spring Boot:
- Create an interceptor class: Create a class that implements the HandlerInterceptor interface or extends the HandlerInterceptorAdapter class provided by Spring.
public class CustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// Logic to be executed before the request is processed
return true; // Return 'true' to allow the request to proceed, or 'false' to stop processing the request
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// Logic to be executed after the request is processed, but before the view is rendered
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// Logic to be executed after the request is completed
}
}
Register the interceptor: In your Spring Boot application, create a configuration class that extends WebMvcConfigurerAdapter (deprecated in newer versions) or implements WebMvcConfigurer. Override the addInterceptors method and register your interceptor.
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Autowired
private CustomInterceptor customInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(customInterceptor)
.addPathPatterns("/**"); // Add patterns to specify which requests should be intercepted
}
}
Customize the interceptor: You can further customize your interceptor by adding conditions to apply the interceptor only to specific URLs or URL patterns, excluding certain URLs, or setting the order in which multiple interceptors should be executed.
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(customInterceptor)
.addPathPatterns("/api/**") // Intercept requests starting with '/api/'
.excludePathPatterns("/api/public/**") // Exclude requests starting with '/api/public/'
.order(1); // Set the order of execution, if you have multiple interceptors
}
Test the interceptor: Start your Spring Boot application and send requests to the URLs that match the interceptor’s configured patterns. The interceptor methods (preHandle, postHandle, afterCompletion) will be executed accordingly.
How to override and replace Tomcat embedded server?
To override and replace the default embedded Tomcat server in a Spring Boot application, you need to configure and provide a different server implementation. Here’s how you can do it:
- Exclude the default Tomcat dependency: In your pom.xml file, exclude the default Tomcat dependency that is automatically added by Spring Boot.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
Add a dependency for an alternative server: Add a dependency for the alternative server implementation you want to use. For example, if you want to use Jetty, add the Jetty dependency.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
Note: Make sure to choose a server implementation that is compatible with Spring Boot and meets your requirements.
Configure the server in the application properties: In your application.properties or application.yml file, configure the server-specific properties. For example, if you’re using Jetty, you can configure Jetty-specific properties.
# application.properties
server.port=8080
server.jetty.acceptors=2
server.jetty.selectors=4
(Optional) Customize server configuration: If you need to customize the server configuration further, you can create a configuration class that implements WebServerFactoryCustomizer and configure the server programmatically.
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.embedded.jetty.JettyServletWebServerFactory;
import org.springframework.stereotype.Component;
@Component
public class JettyServerCustomizer implements WebServerFactoryCustomizer<JettyServletWebServerFactory> {
@Override
public void customize(JettyServletWebServerFactory factory) {
// Customize the Jetty server configuration
factory.setThreadPool(new QueuedThreadPool(100));
// …
}
}
Note: This step is optional and depends on your specific customization needs.
- Run the application: Start your Spring Boot application, and it will now use the alternative server implementation (e.g., Jetty) instead of the default embedded Tomcat server.
That’s it! With these steps, you have overridden and replaced the default embedded Tomcat server with an alternative server implementation in your Spring Boot application.
How @springbootapplication annotation works internally?
The `@SpringBootApplication` annotation is a combination of multiple annotations: `@Configuration`, `@EnableAutoConfiguration`, and `@ComponentScan`.
Here’s a brief explanation of how `@SpringBootApplication` works internally:
1. `@Configuration`: This annotation indicates that the annotated class contains Spring configuration. It allows the class to define beans and other Spring-related configurations.
2. `@EnableAutoConfiguration`: This annotation enables Spring Boot’s auto-configuration feature. It automatically configures various components and dependencies based on the classpath and project dependencies. It sets up sensible defaults and reduces the need for manual configuration.
3. `@ComponentScan`: This annotation instructs Spring to scan and discover components, such as controllers, services, and repositories, in the specified base packages. It allows Spring to find and manage these components as part of the application’s context.
By combining these three annotations into `@SpringBootApplication`, you can configure your Spring Boot application, enable automatic configuration, and enable component scanning in a single line. It simplifies the application setup and reduces the amount of boilerplate code needed to configure and bootstrap a Spring Boot application.
How to use properties defined in application properties in Java class?
To use a property defined in the application.properties file in a Java class, you can make use of the @Value annotation.
Here’s a brief explanation of how to use a property defined in application.properties:
- Define the property in application.properties
myapp.title=My Application
Inject the property value using @Value annotation in your Java class:
@Value(“${myapp.title}”)
private String appTitle;
- This injects the value of the myapp.title property into the appTitle variable.
That’s it! You can now use the appTitle variable in your Java class, and it will hold the value defined in the application.properties file.
What is @RestController annotation in Springboot?
The `@RestController` annotation in Spring Boot is used to define a class as a RESTful controller. It combines the `@Controller` and `@ResponseBody` annotations, making it convenient for building RESTful APIs.
Here’s a brief explanation of the `@RestController` annotation:
- `@Controller`: Indicates that the annotated class is a controller component in the MVC pattern.
- `@ResponseBody`: Specifies that the return value of the controller methods should be serialized directly into the response body.
By using `@RestController`, you can create a controller class where each method represents a specific API endpoint, and the return value of those methods will be automatically converted to the appropriate format (e.g., JSON/XML) and sent as the response body.
In summary, the `@RestController` annotation simplifies the development of RESTful APIs in Spring Boot by combining the `@Controller` and `@ResponseBody` annotations, allowing for a more concise and straightforward approach to building web APIs.
Free PDF’s from @javinpaul from @javarevisited
Grokking the Java Interview [Free Sample Copy]
Grokking the Spring Boot Interview [Free Sample Copy]
Are you preparing for a job interview as a Java developer? Congratulations! To help you succeed in your interview, we have compiled a comprehensive list of top Java developer interview questions. Whether you’re a beginner or an experienced developer, these questions cover a wide range of Java concepts, coding techniques, and best practices. From core Java to advanced topics like multithreading, exception handling, and design patterns, this article will equip you with the knowledge and confidence to showcase your Java expertise. Dive in and prepare yourself to excel in your next Java developer interview!
Thanks for reading
- 👏 Please clap for the story and subscribe 👉
- 📰 Read more content on my Medium (30+ stories on Java Developer interview)
Find my books: