Spring Boot is a project that makes it easy to create stand-alone, production-grade Spring-based applications with minimal configuration.
Example: A Spring Boot application can be started with just a main() method and run on an embedded Tomcat server.
Simplifies configuration, provides an embedded server, and reduces boilerplate code. It also offers production-ready features like health checks and metrics.
Example: With Spring Boot, you don’t need to configure dispatcher-servlet.xml or manually deploy WAR files, as it can run with an embedded server like Tomcat or Jetty.
Auto Configuration: Automatically configures components based on the dependencies on the classpath. Starter Dependencies: Provides predefined templates for commonly used libraries. Embedded Server: Includes servers like Tomcat, Jetty, or Undertow. Production-Ready Metrics: Integrates health checks and monitoring.
Starters are dependency descriptors that allow you to include related dependencies in one go.
Example: The spring-boot-starter-web dependency includes all necessary libraries to create a web application like Spring MVC and embedded Tomcat.
It's a combination of three annotations: @Configuration, @EnableAutoConfiguration, and @ComponentScan, and is used to mark the main class of a Spring Boot application.
Example: @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
Add the database dependencies in pom.xml or build.gradle, then configure the database connection in application.properties or application.yml.
Example: spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=password
Spring Boot Actuator provides production-ready features like monitoring, health checks, and metrics.
Example: After adding spring-boot-starter-actuator dependency, endpoints like /actuator/health and /actuator/metrics become available for monitoring.
Spring Boot automatically configures beans based on the libraries present on the classpath. This is done using @EnableAutoConfiguration.
Example: If spring-web is on the classpath, Spring Boot configures a DispatcherServlet.
You can disable specific auto-configuration classes by using @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class}).
Profiles in Spring Boot are used to provide different configurations for different environments, like dev, test, and prod.
Example: spring.profiles.active=dev or using the @Profile("dev") annotation.
@RestController is a convenience annotation that combines @Controller and @ResponseBody, used to create RESTful web services.
Example: @RestController public class MyController { @GetMapping("/hello") public String hello() { return "Hello World!"; } }
@RequestBody binds the HTTP request body to a Java object. @ResponseBody binds the return value to the HTTP response body.
Example: @PostMapping("/addUser") public User addUser(@RequestBody User user) { return userRepository.save(user); }
You can handle exceptions using @ControllerAdvice and @ExceptionHandler.
Example: @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity <Object> handleResourceNotFound(ResourceNotFoundException ex) { return new ResponseEntity<>("Resource not found", HttpStatus.NOT_FOUND); } }
Starters are a set of convenient dependency descriptors you can include in your application. They simplify build configurations.
Example: spring-boot-starter-web for web applications, spring-boot-starter-data-jpa for JPA support.
This annotation enables Spring Boot's auto-configuration feature, which automatically configures your Spring application based on the jar dependencies available.
You can configure logging using application.properties or logback-spring.xml.
Example: logging.level.org.springframework=DEBUG logging.file.name=app.log
Spring Boot uses application.properties or application.yml to externalize configuration. You can access properties using the @Value annotation or @ConfigurationProperties.
These files are used to configure your application. Spring Boot automatically loads them and applies the properties defined in them.
You can create a Spring Boot project by visiting https://start.spring.io and selecting dependencies, packaging type, and other configurations. Download the generated project and import it into your IDE.
These annotations are specializations of @Component: @Component:Generic stereotype for any Spring-managed component. @Service:Used to mark service-layer beans. @Repository:Specialization for the persistence layer, which also provides exception translation. @Controller:Used to mark web controllers.
Add the spring-boot-starter-data-jpa and H2 dependencies, then configure it in application.properties.
Example: spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.h2.console.enabled=true
Extend the main class from SpringBootServletInitializer and override the configure method.
Example: @SpringBootApplication public class MyApplication extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { return builder.sources(MyApplication.class); } }
This method is used to launch a Spring Boot application. It starts the embedded server and initializes the Spring context.
You can secure an application using Spring Security. Add spring-boot-starter-security and configure security rules using a class annotated with @EnableWebSecurity.
Spring Boot uses Jackson (by default) to convert Java objects to JSON in REST APIs.
Example: When you return an object from a @RestController, it’s automatically converted to JSON.
@Entity is used to map a Java class to a database table in Spring Data JPA.
Example: @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; }
You can set the custom port using application.properties.
Example: server.port=8081
This annotation is used to write integration tests for Spring Boot applications. It boots the full application context.
/actuator/health: Provides application health information. /actuator/metrics: Provides application metrics like memory, threads, and more.
You can configure CORS globally using the WebMvcConfigurer interface or at the controller level using @CrossOrigin.
Example: @CrossOrigin(origins = "http://localhost:3000") @RestController public class MyController { }
Use MultipartFile in controller methods for file upload.
Example: @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { // process file return "File uploaded successfully!"; }
The @Scheduled annotation is used to create scheduled tasks in Spring Boot.
Example: @Scheduled(fixedRate = 5000) public void printMessage() { System.out.println("Task executed every 5 seconds."); }
Spring Boot uses the core Spring Framework’s dependency injection features with annotations like @Autowired and @Bean.
This annotation is used to bind external properties (from application.properties or application.yml) to Java objects.
Define an HTML file in the src/main/resources/templates directory or customize the ErrorController.
@Qualifier is used to resolve ambiguity when multiple beans of the same type are available.
Spring Boot provides default session management with the option to use HTTP sessions, JDBC-based sessions, or Redis for session persistence.
Spring Boot DevTools is a module that provides hot swapping, live reload, and automatic restarts for faster development.
Spring HATEOAS provides support for creating REST APIs with hypermedia controls. Include spring-boot-starter-hateoas and use EntityModel to add links to resources.
You can access environment variables using the Environment object or the @Value annotation.
This annotation is used to conditionally enable beans based on a property’s presence or value in application.properties.
You can externalize configuration using application.properties, application.yml, command-line arguments, or environment variables.
This annotation is used to enable JPA repositories in Spring Data JPA.
Use annotations like @Valid and @Validated to handle validation, along with constraint annotations such as @NotNull and @Size.
@Bean is used to indicate that a method produces a bean to be managed by the Spring container.
Use Spring’s caching abstraction by annotating methods with @Cacheable and enabling caching using @EnableCaching.
It includes testing libraries like JUnit, Mockito, and Spring Test for writing unit and integration tests.
Use @EnableAsync at the configuration class level and @Async at the method level.
These are used to convert HTTP request/response bodies into Java objects (deserialization) and vice versa (serialization). Spring Boot uses HttpMessageConverters like Jackson or Gson by default.
The spring-boot-starter-parent is a special starter that provides default configurations for Maven or Gradle, such as plugin configurations and default dependencies.
Use Spring Security, OAuth 2.0, JWT (JSON Web Token), and HTTPS to secure API endpoints. Apply role-based access control and CSRF protection.
Implement versioning via URI (e.g., /api/v1/resource), request headers, or query parameters to support multiple versions simultaneously.
Use MultipartFile in Spring Boot, set file size limits in application.properties, and consider streaming to avoid memory issues during large uploads.
Implement pagination using Pageable in Spring Data with page and size query parameters. Add filtering with query parameters for fields and criteria.
Use optimistic locking with versioning in JPA or pessimistic locking to ensure data consistency during concurrent updates.
Use caching (e.g., Redis, Ehcache), pagination, optimize database queries with JOIN or INDEX, and apply compression (e.g., GZIP). Also, consider asynchronous processing for long-running tasks.
Implement global exception handling using @ControllerAdvice and @ExceptionHandler to create uniform error responses (HTTP status codes, error messages, and error codes).
Use token-based authentication with JWT (JSON Web Token). Validate the token on each request without storing user sessions on the server.
Implement asynchronous processing with a task queue. Return a 202 Accepted status with a location header to check task progress via polling or webhooks.
Implement the PATCH HTTP method, where only the modified fields are sent in the request body. Use libraries like Jackson to merge partial updates into the existing entity.
Implement rate limiting using libraries like Bucket4J, Redis, or API gateways (e.g., Kong, NGINX). Use headers to communicate rate limits to clients.
Use Spring Boot Actuator to expose health endpoints (/actuator/health) and metrics (/actuator/metrics). Integrate with monitoring systems like Prometheus or Grafana.
Use Spring’s LocaleResolver to detect the locale from headers or request parameters and load messages from localized property files.
Use Spring’s @Transactional annotation to manage transaction boundaries and rollback if any operation fails. Use two-phase commits for distributed transactions.
Use Spring HATEOAS library to add links (like self, next, previous) to API responses. This helps clients navigate through related resources and actions.
Use annotations like @Valid and @Validated along with constraint annotations such as @NotNull, @Min, and @Size. Handle validation errors globally using @ControllerAdvice.
Use @RequestMapping or @GetMapping with produces and consumes attributes. Configure HttpMessageConverters in Spring to support different content types like JSON and XML.
Set timeouts for REST calls using libraries like RestTemplate or WebClient. Configure connection, read, and write timeouts to avoid blocking the application for long durations.
Use POST or PUT to accept bulk data, process it asynchronously, and return a 202 Accepted status. Provide a mechanism for clients to check the status of the bulk operation.
For POST requests, implement idempotency by generating unique request IDs (Idempotency Key) and tracking them server-side to ensure the operation is only executed once.