Top 100 Spring Boot Interview Questions And Answers

Spring Boot Interview Questions
Contents show

1. What is Spring Boot?

Explanation:

Spring Boot is an extension of the Spring framework that simplifies the initial setup and development of new Spring applications. The major advantage is that it minimizes boilerplate code, annotations, and XML configuration.

Official Reference:

Spring Boot Overview


2. How to Create a Simple REST Endpoint?

Code Snippet:

@RestController
public class HelloWorldController {
    @GetMapping("/hello")
    public String helloWorld() {
        return "Hello, World!";
    }
}

Explanation:

The @RestController annotation is used to define a controller and the @GetMapping annotation maps HTTP GET requests onto the helloWorld method.

Official Reference:

Building RESTful Web Services


3. What is Dependency Injection?

Explanation:

Dependency Injection (DI) is a design pattern where dependencies are injected into a class from outside. Spring uses DI extensively to achieve Inversion of Control.

Official Reference:

Dependency Injection


4. How to Configure a Data Source?

Code Snippet:

@Configuration
public class DataSourceConfig {
  @Bean
  public DataSource getDataSource() {
    DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
    dataSourceBuilder.driverClassName("org.h2.Driver");
    dataSourceBuilder.url("jdbc:h2:mem:test");
    dataSourceBuilder.username("SA");
    dataSourceBuilder.password("");
    return dataSourceBuilder.build();
  }
}

Explanation:

The @Configuration and @Bean annotations allow you to specify custom beans in the Spring context. This example creates a new DataSource bean.

Official Reference:

Configuring a DataSource


5. How to Use JPA Repository?

Code Snippet:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

Explanation:

JpaRepository provides methods like save(), findAll(), findById(), etc., which can be used directly in the service classes. By extending JpaRepository, you can handle most common database operations without writing custom DAO code.

Official Reference:

Spring Data JPA


6. What are Actuators?

Explanation:

Spring Boot Actuators offer production-ready features such as metrics, health checks, and application environment information.

Official Reference:

Spring Boot Actuator


7. How to Enable Spring Boot Actuator?

Code Snippet:

Add the following dependency in your pom.xml:

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

Explanation:

By adding the spring-boot-starter-actuator dependency, you enable a range of production-ready features.

Official Reference:

Spring Boot Actuator


8. How to Customize the Spring Boot Banner?

Explanation:

You can customize the Spring Boot banner by placing a banner.txt file in the src/main/resources directory. You can also set spring.banner.location property to specify a file location.

Official Reference:

Customizing the Banner


9. What is @SpringBootApplication Annotation?

Explanation:

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan together. It marks the main class as a Spring Boot application.

Official Reference:

@SpringBootApplication


10. What is Thymeleaf?

Explanation:

Thymeleaf is a Java-based templating engine used in Spring Boot projects to serve HTML views. It can work directly with templates and allows the application of data and logic server-side before sending HTML to the client.

Official Reference:

Thymeleaf + Spring


11. How to Enable Caching in Spring Boot?

Code Snippet:

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

Explanation:

The @EnableCaching annotation turns on Spring Frameworkโ€™s caching support.

Official Reference:

Caching


12. How to Validate Form Inputs?

Code Snippet:

public class UserForm {
  @NotEmpty
  private String username;

  // getters and setters
}

Explanation:

Spring Boot provides validation powered by Hibernate Validator. Annotations like @NotEmpty, @Email, and @Min can validate form inputs.

Official Reference:

Validation


13. How to Handle Exceptions?

Code Snippet:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = {Exception.class})
    public ResponseEntity<Object> handleAnyException(Exception ex) {
        return new ResponseEntity<>(ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Explanation:

Using @ControllerAdvice and @ExceptionHandler annotations, you can handle exceptions globally across all controllers.

Official Reference:

Exception Handling


14. How to Secure Spring Boot Application?

Explanation:

Spring Boot can be secured by adding Spring Security as a dependency and then configuring it in an @Configuration annotated class.

Official Reference:

Spring Security


15. How to Serve Static Resources?

Explanation:

Static resources like HTML, CSS, and JavaScript files can be placed under /static, /public, or /resources directories in the classpath. Spring Boot automatically serves them.

Official Reference:

Serving Static Resources


16. What is AOP?

Explanation:

Aspect-Oriented Programming (AOP) in Spring Boot provides a way to define cross-cutting concerns like logging and security.

Official Reference:

AOP


17. How to Create Asynchronous Methods?

Code Snippet:

@EnableAsync
@SpringBootApplication
public class AsyncApplication { /* ... */ }

@Async
public Future<String> asyncMethod() { /* ... */ }

Explanation:

@EnableAsync and @Async annotations are used to create asynchronous methods in Spring Boot.

Official Reference:

Asynchronous Methods


18. What is @Scheduled?

Code Snippet:

@Scheduled(fixedRate = 5000)
public void runTask() {
  // Task logic
}

Explanation:

@Scheduled annotation is used to schedule tasks at fixed intervals or cron expressions.

Official Reference:

Scheduling


19. How to Customize JSON Response?

Code Snippet:

@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {
  private String name;
  private String email;
}

Explanation:

The @JsonInclude annotation from Jackson can customize JSON responses. Here it ignores null fields.

Official Reference:

Jackson Annotations


20. How to Configure Multiple Data Sources?

Code Snippet:

@Configuration
public class MultipleDataSourceConfig { /* ... */ }

Explanation:

You can configure multiple data sources using @Primary and `@Qualifier

` annotations along with custom configuration classes.

Official Reference:

Data Access


21. What is YAML in Spring Boot?

Explanation:

YAML (Yet Another Markup Language) can be used in place of properties files. Spring Boot supports both .properties and .yml files for configuration.

Official Reference:

YAML


22. What is @Repository?

Explanation:

The @Repository annotation marks a class as a repository, which serves as a mechanism for encapsulating storage, retrieval, and search behavior for data.

Official Reference:

@Repository


23. How to Perform Unit Testing?

Code Snippet:

@SpringBootTest
public class MyServiceTest {

  @Autowired
  private MyService myService;

  @Test
  public void testMethod() {
    // Test logic
  }
}

Explanation:

Spring Boot offers @SpringBootTest for unit testing along with JUnit. The @Autowired annotation is used to inject components for the test.

Official Reference:

Testing


24. How to Rollback Transactions?

Code Snippet:

@Transactional(rollbackFor = Exception.class)
public void someBusinessLogic() {
  // code
}

Explanation:

Use the @Transactional annotation to define the scope of a transaction. By specifying rollbackFor, you can configure it to rollback for specific exceptions.

Official Reference:

Transactions


25. How to Configure CORS?

Code Snippet:

@Configuration
public class CorsConfig {
  @Bean
  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
          .allowedMethods("GET", "POST");
      }
    };
  }
}

Explanation:

Cross-Origin Resource Sharing (CORS) can be configured using the addCorsMappings method in a WebMvcConfigurer bean.

Official Reference:

CORS Support


26. What are Actuators?

Explanation:

Spring Boot Actuators provide production-ready features like monitoring, metrics gathering, and application environment insights.

Official Reference:

Actuator


27. What is @Value Annotation?

Code Snippet:

@Value("${custom.property}")
private String customProperty;

Explanation:

The @Value annotation allows you to inject values from properties files into your Spring components.

Official Reference:

@Value


28. How to Customize Startup Banner?

Explanation:

To customize the startup banner, place a banner.txt file inside src/main/resources. The text in this file will replace the default Spring Boot banner.

Official Reference:

Custom Banner


29. How to Send Email?

Code Snippet:

@Autowired
private JavaMailSender mailSender;

public void sendEmail() {
  SimpleMailMessage message = new SimpleMailMessage();
  message.setTo("recipient@example.com");
  // set subject, text, etc.
  mailSender.send(message);
}

Explanation:

Spring Boot provides easy mail sending via the JavaMailSender interface, which can be auto-wired into your components.

Official Reference:

Mail Sending


30. What is Swagger and How to Integrate it?

Explanation:

Swagger is used for API documentation. It can be easily integrated into a Spring Boot application using the springfox-boot-starter dependency.

Official Reference:

Swagger


31. What is a Filter in Spring Boot?

Explanation:

Filters in Spring Boot are used for pre- and post-processing of requests. Implement javax.servlet.Filter and override its methods for custom functionality.

Official Reference:

Filters


32. How to Schedule Tasks?

Code Snippet:

@Scheduled(fixedRate = 5000)
public void performTask() {
    // Task logic
}

Explanation:

The @Scheduled annotation in Spring Boot allows you to run methods at specific intervals. Use fixedRate to set the rate in milliseconds.

Official Reference:

Scheduling


33. What is Thymeleaf?

Explanation:

Thymeleaf is a server-side Java template engine used for web applications in Spring Boot. It integrates seamlessly with Spring MVC.

Official Reference:

Thymeleaf


34. How to Serve Static Content?

Explanation:

Place static content like HTML, CSS, or images in the src/main/resources/static directory. Spring Boot will automatically serve them.

Official Reference:

Static Content


35. What is YAML?

Explanation:

YAML (Yet Another Markup Language) is a human-readable data format. It is used in Spring Boot as an alternative to properties files for configuration.

Official Reference:

YAML


36. How to Configure Profiles?

Code Snippet:

@Profile("dev")
@Configuration
public class DevConfig {
    // Configuration for 'dev' profile
}

Explanation:

Spring Boot allows you to define configuration for specific profiles using the @Profile annotation.

Official Reference:

Profiles


37. What is @ControllerAdvice?

Explanation:

The @ControllerAdvice annotation allows you to define global exception handling logic across all @Controller classes.

Official Reference:

@ControllerAdvice


38. How to Enable Caching?

Code Snippet:

@EnableCaching
@Configuration
public class CacheConfig {
    // Caching configuration
}

Explanation:

Use the @EnableCaching annotation to enable caching support in your Spring Boot application.

Official Reference:

Caching


39. How to Use WebSocket?

Explanation:

WebSockets provide a real-time, full-duplex communication channel. Spring Boot provides easy integration through the spring-boot-starter-websocket dependency.

Official Reference:

WebSocket


40. What are Environment Abstractions?

Explanation:

Spring Boot provides a set of environment abstractions for properties, profiles, and property sources. You can inject the Environment object to access these features.

Official Reference:

Environment

For deeper understanding and practical insights, it is highly recommended to consult the official documentation provided in the links.


41. How to Enable Security in Spring Boot?

Code Snippet:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // Security configurations
}

Explanation:

@EnableWebSecurity annotation and extending WebSecurityConfigurerAdapter are essential for adding custom security configurations.

Official Reference:

Security


42. What is Dependency Injection?

Explanation:

Dependency Injection is a design pattern where the framework injects dependencies into a class, rather than the class creating them itself. Spring Boot heavily relies on this concept.

Official Reference:

Dependency Injection


43. How to Deploy Spring Boot Application?

Explanation:

Spring Boot applications can be deployed in multiple ways, such as standalone JARs or WAR files, or on cloud platforms like AWS and Heroku.

Official Reference:

Deployment


44. What are Cross-Origin Requests?

Code Snippet:

@CrossOrigin(origins = "http://example.com")
@RestController
public class MyController {
    // Controller methods
}

Explanation:

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers. Use @CrossOrigin to handle CORS in Spring Boot.

Official Reference:

CORS


45. What is @Autowired?

Code Snippet:

@Autowired
private MyService myService;

Explanation:

@Autowired is used for dependency injection in Spring Boot. It auto-wires a bean by type.

Official Reference:

Autowired


46. What are Actuators?

Explanation:

Spring Boot Actuators are production-ready features like health checks and metrics. Include spring-boot-starter-actuator for these capabilities.

Official Reference:

Actuators


47. What is AOP?

Explanation:

Aspect-Oriented Programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of concerns. Spring Boot provides native support for AOP.

Official Reference:

AOP


48. How to Test Spring Boot Applications?

Code Snippet:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTests {
    // Test methods
}

Explanation:

Spring Boot provides a robust testing framework. Use @RunWith and @SpringBootTest for comprehensive integration testing.

Official Reference:

Testing


49. What is JPA?

Explanation:

Java Persistence API (JPA) is a specification for object-relational mapping in Java. Spring Boot provides native support via Spring Data JPA.

Official Reference:

JPA


50. What is @RequestMapping?

Code Snippet:

@RequestMapping("/api")
public class ApiController {
    // Controller methods
}

Explanation:

@RequestMapping is used to map web requests. It can be applied at both class and method level.

Official Reference:

RequestMapping


51. What is the @RestController Annotation?

Code Snippet:

@RestController
public class MyController {
    // Controller methods
}

Explanation:

@RestController is a specialized version of @Controller that assumes @ResponseBody semantics, returning data directly to the caller.

Official Reference:

RestController


52. What are Spring Boot Profiles?

Explanation:

Spring Boot Profiles provide a way to segregate parts of your application configurations and make it available only in certain environments.

Official Reference:

Profiles


53. How to Use @Value Annotation?

Code Snippet:

@Value("${my.property}")
private String myProperty;

Explanation:

The @Value annotation is used to inject property values from property files into Spring managed beans.

Official Reference:

Value


54. What is Spring Data JPA?

Explanation:

Spring Data JPA is a part of the larger Spring Data family. It makes it easy to implement JPA-based repositories and provides many out-of-the-box features.

Official Reference:

Spring Data JPA


55. How to Implement Exception Handling?

Code Snippet:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handleException(Exception e) {
        // Handle exception
    }
}

Explanation:

Using @ControllerAdvice and @ExceptionHandler, you can define a global error handling mechanism in Spring Boot applications.

Official Reference:

Exception Handling


56. How to Configure Multiple Data Sources?

Code Snippet:

@Configuration
public class DataSourceConfig {
    @Primary
    @Bean(name = "dataSource")
    public DataSource dataSource() {
        // Configure primary data source
    }

    @Bean(name = "secondaryDataSource")
    public DataSource secondaryDataSource() {
        // Configure secondary data source
    }
}

Explanation:

Spring Boot allows you to configure multiple data sources using the @Primary annotation to distinguish them.

Official Reference:

Multiple Data Sources


57. How to Schedule Tasks?

Code Snippet:

@EnableScheduling
public class ScheduleConfig {
    @Scheduled(fixedRate = 1000)
    public void performTask() {
        // Perform scheduled task
    }
}

Explanation:

Use @EnableScheduling and @Scheduled annotations to create scheduled tasks in Spring Boot.

Official Reference:

Scheduling


58. What is Spring Security OAuth2?

Explanation:

Spring Security OAuth2 is a framework for building OAuth2 authorization servers and clients in Spring Boot.

Official Reference:

OAuth2


59. What is the Role of pom.xml in Spring Boot?

Explanation:

pom.xml is a Maven Project Object Model file. It defines project resources, plugins, and dependencies, including Spring Boot Starter dependencies.

Official Reference:

Maven


60. What is Spring Boot DevTools?

Explanation:

Spring Boot DevTools is a set of tools that make the development process easier by providing auto-reloads, improved debugging, and additional developer-friendly features.

Official Reference:

DevTools


61. What is the Spring Boot Actuator?

Explanation:

Spring Boot Actuator provides various production-ready features like metrics, health checks, and application environment details right out of the box.

Official Reference:

Spring Boot Actuator


62. How to Enable Caching?

Code Snippet:

@EnableCaching
public class CachingConfig {
    // Configuration
}

Explanation:

Use the @EnableCaching annotation to enable Springโ€™s annotation-driven cache management capability.

Official Reference:

Caching


63. What is CORS and How to Enable it?

Code Snippet:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("http://domain.com");
    }
}

Explanation:

CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers. Spring Boot provides first-class support for CORS via the WebMvcConfigurer.

Official Reference:

CORS


64. What is the @Query Annotation?

Code Snippet:

public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT u FROM User u WHERE u.email = ?1")
    User findByEmail(String email);
}

Explanation:

@Query annotation allows you to write custom queries using JPQL (Java Persistence Query Language).

Official Reference:

@Query


65. How to Use Application Properties?

Explanation:

You can define properties in application.properties file and access them using the @Value annotation or Environment object.

Official Reference:

Properties


66. How to Customize Spring Boot Banner?

Explanation:

You can customize the Spring Boot startup banner by placing a banner.txt file in the src/main/resources directory.

Official Reference:

Banner


67. What is AOP (Aspect-Oriented Programming) in Spring Boot?

Code Snippet:

@Aspect
public class LoggingAspect {
    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        // Logging logic here
    }
}

Explanation:

AOP allows you to define cross-cutting concerns like logging, security, etc., separate from the main business logic.

Official Reference:

AOP


68. How to Upload Files using Spring Boot?

Code Snippet:

@RestController
public class FileUploadController {
    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        // File handling code
    }
}

Explanation:

You can handle file uploads in Spring Boot using the MultipartFile interface.

Official Reference:

File Upload


69. How to Write Custom Queries in Repository?

Code Snippet:

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByNameAndEmail(String name, String email);
}

Explanation:

Spring Data JPA repositories support custom query methods defined by extending method names, as shown above.

Official Reference:

Query Methods


70. What are Spring Profiles?

Explanation:

Spring Profiles provide a way to segregate parts of your application configuration, making it possible to run under different environments.

Official Reference:

Spring Profiles


71. How to Implement Asynchronous Methods?

Code Snippet:

@Async
public CompletableFuture<String> asyncMethod() {
    // Async operations
}

Explanation:

You can make a method asynchronous by annotating it with @Async. Ensure that you also annotate a configuration class with @EnableAsync.

Official Reference:

Asynchronous Methods


72. What is Thymeleaf and How is it Used in Spring Boot?

Explanation:

Thymeleaf is a Java-based templating engine used in Spring Boot to serve up HTML views. It integrates well with Spring MVC.

Official Reference:

Thymeleaf


73. How to Handle Exceptions?

Code Snippet:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = {Exception.class})
    public ResponseEntity<Object> handleException(Exception ex) {
        // Exception handling code
    }
}

Explanation:

You can globally handle exceptions using @ControllerAdvice and @ExceptionHandler annotations. This allows for a centralized exception-handling mechanism.

Official Reference:

Exception Handling


74. How to Configure Spring Security?

Code Snippet:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated()
            .and().httpBasic();
    }
}

Explanation:

Spring Security can be configured by extending WebSecurityConfigurerAdapter and overriding its methods.

Official Reference:

Spring Security


75. How to Use WebSockets?

Code Snippet:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }
}

Explanation:

Spring Boot provides support for WebSocket-based messaging using the @EnableWebSocketMessageBroker annotation.

Official Reference:

WebSockets


76. What is JdbcTemplate?

Explanation:

JdbcTemplate is a Spring utility that simplifies database access and error handling in JDBC.

Official Reference:

JdbcTemplate


77. How to Validate User Input?

Code Snippet:

public class User {
    @NotNull
    @Size(min=2, max=30)
    private String name;
}

Explanation:

Spring Boot provides built-in support for JSR 380 Bean Validation. Annotations such as @NotNull, @Size, etc., can be used for validation.

Official Reference:

Validation


78. How to Schedule Tasks?

Code Snippet:

@Scheduled(fixedRate = 5000)
public void performTask() {
    // Task logic here
}

Explanation:

Scheduled tasks can be created by annotating a method with @Scheduled and specifying a fixed rate or cron expression.

Official Reference:

Scheduling


79. How to Enable HTTPS?

Explanation:

To enable HTTPS, you need to configure the application properties with the keystore and SSL details.

Official Reference:

HTTPS


80. How to Access Command-line Arguments?

Code Snippet:

@SpringBootApplication
public class Application implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) {
        String[] sourceArgs = args.getSourceArgs();
        // Process arguments
    }
}

Explanation:

Spring Boot exposes command-line arguments as an ApplicationArguments bean that can be injected into any managed bean.

Official Reference:

Command-line Arguments


81. How to Test a Spring Boot Application?

Code Snippet:

@SpringBootTest
public class MyApplicationTests {
    @Autowired
    private MyService myService;

    @Test
    public void testMyService() {
        assertEquals("expectedValue", myService.someMethod());
    }
}

Explanation:

Spring Boot provides @SpringBootTest annotation for end-to-end testing. You can use standard JUnit annotations to write test methods.

Official Reference:

Testing in Spring Boot


82. What is Spring Data JPA?

Explanation:

Spring Data JPA is a part of the Spring Data project that simplifies data access within the Spring application, providing a powerful repository and custom object-mapping abstractions.

Official Reference:

Spring Data JPA


83. How to Implement Pagination in Spring Boot?

Code Snippet:

public Page<User> findPaginated(Pageable pageable) {
    return userRepository.findAll(pageable);
}

Explanation:

Spring Data JPA repository interfaces have methods for fetching data in a paginated format. You pass a Pageable object to findAll() to get a Page object that represents a paginated dataset.

Official Reference:

Spring Data Pagination


84. What is Spring Boot Actuator?

Explanation:

Spring Boot Actuator provides production-ready features such as monitoring, metrics, and application environment details out of the box.

Official Reference:

Spring Boot Actuator


85. What is CORS and How to Handle it?

Code Snippet:

@CrossOrigin(origins = "http://example.com")
@RestController
public class MyController {
    // Controller methods
}

Explanation:

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers. Spring Boot provides @CrossOrigin annotation to specify allowed origins.

Official Reference:

CORS support


86. How to Use Spring Boot with Docker?

Explanation:

Spring Boot applications can be containerized using Docker. You can create a Dockerfile to build a Docker image for your application.

Official Reference:

Spring Boot with Docker


87. How to Internationalize a Spring Boot App?

Code Snippet:

@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setDefaultLocale(Locale.US);
    return localeResolver;
}

Explanation:

Spring Boot provides Internationalization (i18n) support through MessageSource and LocaleResolver beans.

Official Reference:

Internationalization


88. What is Aspect-Oriented Programming (AOP) in Spring?

Explanation:

AOP allows you to define cross-cutting concerns such as logging, security, and transactions separately from your business logic.

Official Reference:

Aspect Oriented Programming (AOP)


89. How to Create a Batch Service?

Code Snippet:

@Configuration
@EnableBatchProcessing
public class BatchConfig {
    // Batch job configurations
}

Explanation:

Spring Boot supports batch processing through the Spring Batch project. Use @EnableBatchProcessing to enable batch features.

Official Reference:

Spring Batch


90. How to Enable Caching?

Code Snippet:

@EnableCaching
public class CacheConfig {
    // Cache configurations
}

Explanation:

Spring Boot provides caching abstraction to improve performance. Use @EnableCaching to enable caching.

Official Reference:

Caching


91. How to Upload a File in Spring Boot?

Code Snippet:

@PostMapping("/upload")
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
    // File upload logic
    return ResponseEntity.ok("File uploaded");
}

Explanation:

Spring Boot enables file uploading through the MultipartFile interface. The @RequestParam annotation is used to specify the name of the form field that holds the file.

Official Reference:

File Upload


92. What is the @Query Annotation?

Code Snippet:

@Query("SELECT u FROM User u WHERE u.email = ?1")
List<User> findUsersByEmail(String email);

Explanation:

The @Query annotation in Spring Data JPA is used for specifying JPQL (Java Persistence Query Language) queries directly on repository methods.

Official Reference:

Spring Data JPA Query


93. How to Implement Security in Spring Boot?

Code Snippet:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // Security configurations
}

Explanation:

Spring Boot uses Spring Security to add security features. The @EnableWebSecurity annotation and extending WebSecurityConfigurerAdapter allow you to customize security settings.

Official Reference:

Spring Security


94. What is Websocket in Spring Boot?

Explanation:

Websocket provides full-duplex communication over a single TCP connection. Spring Boot supports Websocket for real-time updates and interaction.

Official Reference:

Spring Websocket


95. What are Spring Boot Starters?

Explanation:

Spring Boot Starters are a set of convenient dependency descriptors to simplify your build configuration. They automatically manage dependencies and configurations.

Official Reference:

Spring Boot Starters


96. How to Schedule Jobs in Spring Boot?

Code Snippet:

@Scheduled(fixedRate = 5000)
public void scheduleTask() {
    // Scheduled task code
}

Explanation:

Spring Boot has built-in support for scheduling tasks using the @Scheduled annotation, which can be used to specify the frequency and parameters of a job.

Official Reference:

Scheduling


97. What is HATEOAS in Spring Boot?

Explanation:

HATEOAS (Hypermedia as the Engine of Application State) is a REST architecture principle. Spring Boot provides the Spring HATEOAS project for creating REST representations that follow the HATEOAS principle.

Official Reference:

Spring HATEOAS


98. How to Use Spring Boot Profiles?

Code Snippet:

@Profile("dev")
@Configuration
public class DevConfig {
    // Development configurations
}

Explanation:

Spring Boot allows you to define different configurations for different environments using profiles. The @Profile annotation specifies which profile the configuration belongs to.

Official Reference:

Spring Boot Profiles


99. How to Create a Custom Error Page?

Code Snippet:

@Controller
public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController {
    // Custom error logic
}

Explanation:

You can customize error handling by implementing the ErrorController interface. This allows you to define custom error pages.

Official Reference:

Error Handling


100. How to Validate Form Input?

Code Snippet:

public class UserForm {
    @NotNull
    @Size(min=2, max=30)
    private String name;
    // Other fields and validations
}

Explanation:

Spring Boot allows you to validate form input using annotations like @NotNull, @Size, etc., which can be used in your model class.

Official Reference:

Validation