Advanced Spring Boot Interview Questions
On this page20
- 1How does Spring Boot achieve auto-configuration?
- 2What is the difference between @SpringBootApplication and @EnableAutoConfiguration?
- 3How does Spring Boot handle security?
- 4How do you implement exception handling in Spring Boot?
- 5How do you monitor a Spring Boot application in production?
- 6What is the difference between @RestController and @Controller?
- 7How do you configure multiple data sources in Spring Boot?
- 8How do you implement caching in Spring Boot?
- 9How do you handle circular dependencies in Spring?
- 10What is the difference between @Component, @Service, @Repository, and @Controller?
- 11How do you use profiles in Spring Boot?
- 12How does Spring Boot support asynchronous programming?
- 13How do you secure Actuator endpoints?
- 14How do you test Spring Boot applications?
- 15What is the difference between @RequestParam and @PathVariable?
- 16How do you implement file upload in Spring Boot?
- 17How do you configure a custom banner in Spring Boot?
- 18What is the purpose of @Conditional annotations in Spring Boot?
- 19How do you implement scheduling in Spring Boot?
- 20How do you handle large data sets in Spring Boot?
1. How does Spring Boot achieve auto-configuration?
Spring Boot uses the @EnableAutoConfiguration annotation (part of @SpringBootApplication) to enable auto-configuration. It scans the classpath for dependencies and uses the spring.factories file (in META-INF/) to load @Configuration classes conditionally. These classes use annotations like @ConditionalOnClass, @ConditionalOnMissingBean, and @ConditionalOnProperty to configure beans only when specific conditions are met.
2. What is the difference between @SpringBootApplication and @EnableAutoConfiguration?
- @SpringBootApplication is a combination of:
- @Configuration: Marks the class as a source of bean definitions.
- @EnableAutoConfiguration: Enables Spring Boot’s auto-configuration mechanism.
- @ComponentScan: Scans the package and sub-packages for Spring components.
- @EnableAutoConfiguration is just one part of @SpringBootApplication and focuses solely on enabling auto-configuration.
3. How does Spring Boot handle security?
Spring Boot uses Spring Security for authentication and authorization. By default:
- It secures all endpoints with basic authentication.
- You can customize security by extending WebSecurityConfigurerAdapter or using SecurityFilterChain (from Spring Security 5.7+).
Example:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
4. How do you implement exception handling in Spring Boot?
Use @ControllerAdvice to handle exceptions globally:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundExceptionex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exceptionex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred");
}
}
5. How do you monitor a Spring Boot application in production?
- Use Spring Boot Actuator to expose endpoints for monitoring (e.g., /actuator/health, /actuator/metrics).
- Integrate with tools like Prometheus, Grafana, or New Relic for advanced monitoring.
- Secure Actuator endpoints using Spring Security.
Example:
management.endpoints.web.exposure.include=health,metrics
management.endpoint.health.show-details=always
6. What is the difference between @RestController and @Controller?
- @RestController is a combination of @Controller and @ResponseBody. It is used for RESTful web services and automatically serializes responses to JSON or XML.
- @Controller is used for traditional MVC applications and requires @ResponseBody to return JSON or XML.
7. How do you configure multiple data sources in Spring Boot?
Define multiple DataSource beans and mark one as @Primary. Use @EnableJpaRepositories with basePackages to specify which repository uses which data source.
Example:
@Configuration
public class DataSourceConfig {
@Primary
@Bean(name ="dataSource1")
@ConfigurationProperties(prefix ="spring.datasource1")
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
@Bean(name ="dataSource2")
@ConfigurationProperties(prefix ="spring.datasource2")
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
}
8. How do you implement caching in Spring Boot?
- Add the spring-boot-starter-cache dependency.
- Enable caching with @EnableCaching.
- Use annotations like @Cacheable, @CachePut, and @CacheEvict.
Example:
@Cacheable("users")
public User getUserById(Long id) {
return userRepository.findById(id).orElseThrow();
}
9. How do you handle circular dependencies in Spring?
- Use @Lazy on one of the dependencies to delay initialization.
- Refactor the code to remove the circular dependency.
- Use setter injection instead of constructor injection.
10. What is the difference between @Component, @Service, @Repository, and @Controller?
- @Component: Generic stereotype for any Spring-managed bean.
- @Service: Specialization of @Component for service layer beans.
- @Repository: Specialization of @Component for data access layer beans; adds exception translation.
- @Controller: Specialization of @Component for MVC controllers.
11. How do you use profiles in Spring Boot?
- Define profile-specific property files like application-dev.properties and application-prod.properties.
- Activate a profile using:
- spring.profiles.active=dev in application.properties.
- Environment variables.
- Command-line arguments (--spring.profiles.active=dev).
12. How does Spring Boot support asynchronous programming?
- Use @EnableAsync to enable asynchronous processing.
- Annotate methods with @Async to execute them in a separate thread.
Example:
@EnableAsync
@Configuration
public class AsyncConfig {}
@Async
public void sendEmail(String email) {
// Asynchronous email sending logic
}
13. How do you secure Actuator endpoints?
- Use Spring Security to restrict access to Actuator endpoints.
- Configure security rules in application.properties or application.yml.
Example:
management.endpoints.web.exposure.include=health,info
management.endpoint.health.roles=ADMIN
14. How do you test Spring Boot applications?
- Use @SpringBootTest for integration tests.
- Use @WebMvcTest for controller tests.
- Use @DataJpaTest for JPA repository tests.
- Use MockMvc for simulating HTTP requests.
15. What is the difference between @RequestParam and @PathVariable?
- @RequestParam: Extracts query parameters from the URL.
- @PathVariable: Extracts values from the URL path.
Example:
@GetMapping("/users")
public String getUserByQuery(@RequestParamString name) { ... }
@GetMapping("/users/{id}")
public String getUserById(@PathVariableLong id) { ... }
16. How do you implement file upload in Spring Boot?
Use MultipartFile to handle file uploads:
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
// Save file logic
return"File uploaded successfully";
}
17. How do you configure a custom banner in Spring Boot?
Place a banner.txt file in the src/main/resources directory. You can use ASCII art or text.
18. What is the purpose of @Conditional annotations in Spring Boot?
@Conditional annotations (e.g., @ConditionalOnClass, @ConditionalOnProperty) are used to conditionally load beans based on specific conditions, such as the presence of a class or a property.
19. How do you implement scheduling in Spring Boot?
- Add @EnableScheduling to your configuration class or Main class.
- Use @Scheduled to define scheduled tasks.
Example:
@Component
public class SchedulerConfig {
@Scheduled(fixedRate =5000)
public void scheduledTask() {
System.out.println("Task executed every 5 seconds");
}
}
20. How do you handle large data sets in Spring Boot?
- Use pagination with Pageable in Spring Data JPA.
- Stream data using @Query with Stream return type.
- Use batch processing with Spring Batch for large-scale data processing.
