The Spring Framework is a powerful and comprehensive application framework for Java. It provides a wide range of features to build robust, scalable, and maintainable enterprise-level applications. At its core, Spring is built on the principles of Inversion of Control (IoC) and Dependency Injection (DI), which help in creating loosely coupled applications.
Key Features:
Why use Spring?
Inversion of Control (IoC) is a design principle where the control of object creation and lifecycle is transferred from the application to a container or framework. In traditional programming, the developer creates objects and manages their dependencies. With IoC, the framework takes over this responsibility.
Dependency Injection (DI) is a design pattern that implements IoC. It's the process whereby the Spring container "injects" the dependencies (i.e., other objects) that a bean needs.
Types of Dependency Injection:
Constructor Injection: Dependencies are provided through the class constructor. This is the recommended approach as it ensures that an object is created with all its required dependencies.
@Service public class OrderService { private final OrderRepository orderRepository; @Autowired public OrderService(OrderRepository orderRepository) { this.orderRepository = orderRepository; } }
Setter Injection: Dependencies are injected through setter methods. This is useful for optional dependencies.
@Service public class OrderService { private OrderRepository orderRepository; @Autowired public void setOrderRepository(OrderRepository orderRepository) { this.orderRepository = orderRepository; } }
Field Injection: Dependencies are injected directly into the fields using the @Autowired
annotation. While simple, this approach is generally discouraged because it makes testing more difficult and can hide dependencies.
@Service public class OrderService { @Autowired private OrderRepository orderRepository; }
A Spring Bean is an object that is instantiated, assembled, and otherwise managed by the Spring IoC container. Beans are the fundamental building blocks of any Spring application.
Bean Lifecycle: The lifecycle of a bean is the sequence of events from its instantiation to its destruction.
Lifecycle Callbacks:
@PostConstruct
: A method annotated with @PostConstruct
is executed after the bean has been constructed and its dependencies have been injected.@PreDestroy
: A method annotated with @PreDestroy
is called just before the bean is removed from the container.Example:
@Component public class MyBean { public MyBean() { System.out.println("1. Constructor called"); } @Autowired public void setDependency(MyDependency dependency) { System.out.println("2. Setter for dependency called"); } @PostConstruct public void init() { System.out.println("3. @PostConstruct: Bean is initialized"); } public void doWork() { System.out.println("Bean is doing work..."); } @PreDestroy public void cleanup() { System.out.println("4. @PreDestroy: Bean is about to be destroyed"); } }
Bean scope determines the lifecycle and visibility of a bean in a specific context. Spring supports several scopes:
singleton
: (Default) Only one instance of the bean is created for the entire Spring container.prototype
: A new instance of the bean is created every time it is requested.request
: A new instance is created for each HTTP request. (Web-aware ApplicationContext only)session
: A new instance is created for each HTTP session. (Web-aware ApplicationContext only)application
: A single instance is created for the lifecycle of a ServletContext
. (Web-aware ApplicationContext only)websocket
: A single instance is created for the lifecycle of a WebSocket session. (Web-aware ApplicationContext only)Example of setting scope:
import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Component @Scope("prototype") public class MyPrototypeBean { public MyPrototypeBean() { System.out.println("MyPrototypeBean instance created: " + this); } } @Component @Scope("singleton") // This is the default, so it's optional public class MySingletonBean { public MySingletonBean() { System.out.println("MySingletonBean instance created: " + this); } }
These are stereotype annotations that mark a class as a Spring bean. While @Component
is a generic stereotype, @Service
, @Repository
, and @Controller
are specializations of @Component
for more specific use cases.
@Component
: A generic annotation for any Spring-managed component. It's the base for all other stereotype annotations.@Service
: Indicates that a class is a service, typically used in the business logic layer.@Repository
: Indicates that a class is a repository, responsible for data access. It also enables exception translation for data access exceptions.@Controller
: Indicates that a class is a controller in a Spring MVC application, responsible for handling web requests.Example:
// Generic component @Component public class MyComponent { // ... } // Service layer @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; // Business logic } // Data access layer @Repository public interface UserRepository extends JpaRepository<User, Long> { // Exception translation is automatically enabled } // Web layer @Controller public class UserController { @Autowired private UserService userService; // Request handling methods }
Spring Boot is an extension of the Spring framework that simplifies the development of stand-alone, production-grade Spring-based applications. It takes an "opinionated" view of the Spring platform, which means it makes assumptions about how to configure the application and what dependencies to use.
Key Differences:
Feature | Spring | Spring Boot |
---|---|---|
Configuration | Manual configuration (XML or Java-based) | Automatic configuration (auto-configuration) |
Setup | Requires significant setup and boilerplate | Minimal setup, "just run" applications |
Dependencies | Manual dependency management | Simplified with "starters" |
Server | Requires external server (e.g., Tomcat) | Embedded server (Tomcat, Jetty, Undertow) |
Goal | To provide a flexible and powerful framework | To simplify the development of Spring apps |
Key Features of Spring Boot:
spring-boot-starter-web
includes all the necessary dependencies for building a web application.Aspect-Oriented Programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. AOP breaks down program logic into distinct parts called concerns. The core concern of the application is business logic, while cross-cutting concerns are functionalities that are used across multiple parts of the application, such as logging, security, and transaction management.
Common AOP Concepts:
@Aspect
.@Before
, @After
, @Around
, @AfterReturning
, and @AfterThrowing
.Example of an AOP logging aspect:
@Aspect @Component public class LoggingAspect { private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class); @Pointcut("execution(* com.example.service.*.*(..))") public void serviceLayerExecution() {} @Before("serviceLayerExecution()") public void logBefore(JoinPoint joinPoint) { logger.info("Executing: " + joinPoint.getSignature().toShortString()); } @AfterReturning(pointcut = "serviceLayerExecution()", returning = "result") public void logAfterReturning(JoinPoint joinPoint, Object result) { logger.info("Finished executing: " + joinPoint.getSignature().toShortString()); logger.info("Returned: " + result); } }
Spring MVC (Model-View-Controller) is a web framework that provides a flexible and robust architecture for building web applications. At the heart of Spring MVC is the DispatcherServlet
, which acts as the front controller. It receives all incoming requests and delegates them to the appropriate components for processing.
The request processing workflow in Spring MVC is as follows:
DispatcherServlet
receives the request.DispatcherServlet
consults the HandlerMapping
to determine which controller should handle the request.DispatcherServlet
calls the appropriate Controller
.Controller
processes the request, performs business logic, and returns a ModelAndView
object (or a view name).DispatcherServlet
uses a ViewResolver
to resolve the logical view name into a physical View
implementation.View
is rendered, and the response is sent back to the client.Both @Controller
and @RestController
are used to define controllers in Spring MVC, but they have a key difference in how they handle responses.
@Controller
: A traditional Spring MVC controller that returns a view. The return value of a method is typically a view name, which is then resolved by a ViewResolver
to render a view (e.g., a JSP or Thymeleaf template). To return data directly (like JSON), you need to annotate the method with @ResponseBody
.
@RestController
: A specialized controller used for building RESTful web services. It's a combination of @Controller
and @ResponseBody
. With @RestController
, every method's return value is automatically serialized into the response body (e.g., as JSON), so you don't need to add @ResponseBody
to each method.
For more details on Spring MVC, you can read more about it here.
@Controller Example:
@Controller public class MyViewController { @GetMapping("/hello") public String hello(Model model) { model.addAttribute("message", "Hello from @Controller!"); return "hello-view"; // Returns the view name } @GetMapping("/api/data") @ResponseBody // Required to return data public MyData getData() { return new MyData("some data"); } }
@RestController Example:
@RestController @RequestMapping("/api") public class MyRestController { @GetMapping("/hello") public MyData hello() { return new MyData("Hello from @RestController!"); // Automatically serialized to JSON } }
The @Autowired
annotation is used for automatic dependency injection. It allows Spring to resolve and inject collaborating beans into your bean.
Types of Autowiring:
Constructor Injection: Spring injects dependencies through the constructor. This is the recommended approach.
@Service public class MyService { private final MyRepository repository; @Autowired public MyService(MyRepository repository) { this.repository = repository; } }
Setter Injection: Spring injects dependencies through setter methods.
@Service public class MyService { private MyRepository repository; @Autowired public void setRepository(MyRepository repository) { this.repository = repository; } }
Field Injection: Spring injects dependencies directly into the fields. This is generally discouraged due to testing difficulties.
@Service public class MyService { @Autowired private MyRepository repository; }
Autowiring by Type, Name, and Qualifier:
byType
(Default): Spring looks for a bean of the same type as the property to be injected. If there's more than one bean of the same type, it will throw an exception.byName
: Spring looks for a bean with the same name as the property.@Qualifier
: When there are multiple beans of the same type, @Qualifier
can be used to specify which bean to inject.@Primary
: Can be used on a bean to indicate that it should be the primary choice when multiple candidates are available for autowiring.Example with @Qualifier
:
public interface MessageService { String getMessage(); } @Component("emailService") public class EmailService implements MessageService { public String getMessage() { return "Email message"; } } @Component("smsService") public class SmsService implements MessageService { public String getMessage() { return "SMS message"; } } @Component public class MessageProcessor { private final MessageService messageService; @Autowired public MessageProcessor(@Qualifier("smsService") MessageService messageService) { this.messageService = messageService; } }
For more details on JWT authentication in Spring 6, you can read more about it here.
A Filter
is a Java class that intercepts and processes HTTP requests before they reach the DispatcherServlet
. Spring Security uses a chain of filters to apply security rules.
DelegatingFilterProxy
is a servlet filter that delegates to a Spring-managed bean that implements the Filter
interface. This allows the filter to benefit from Spring's dependency injection and lifecycle management.
The SecurityContextHolder
is where Spring Security stores the details of the currently authenticated user.
The @EnableWebSecurity
annotation is used to enable Spring Security's web security support and provide the Spring MVC integration.
CORS (Cross-Origin Resource Sharing) is a mechanism that allows resources to be requested from another domain. In Spring, you can handle CORS by using the @CrossOrigin
annotation or by configuring it globally in your security configuration.
CSRF (Cross-Site Request Forgery) is an attack that tricks the victim into submitting a malicious request. Spring Security provides CSRF protection by default.
Method security allows you to secure individual methods in your application. You can enable it by using the @EnableGlobalMethodSecurity
annotation and then use annotations like @PreAuthorize
and @PostAuthorize
to secure your methods.
Spring Boot Actuator is a sub-project of Spring Boot that provides production-ready features to help you monitor and manage your application. It exposes a set of endpoints that provide information about the application's health, metrics, configuration, and more.
/health
: Shows application health information./metrics
: Shows various metrics about the application./info
: Displays arbitrary application info./beans
: Displays a complete list of all Spring beans in your application./mappings
: Displays a collated list of all @RequestMapping
paths./configprops
: Displays a collated list of all @ConfigurationProperties
./env
: Displays properties from Spring's ConfigurableEnvironment
./threaddump
: Performs a thread dump./heapdump
: Returns a heap dump file.To enable Actuator endpoints, you need to add the spring-boot-starter-actuator
dependency to your project. By default, only the /health
and /info
endpoints are exposed over HTTP. You can expose other endpoints by setting the management.endpoints.web.exposure.include
property in your application.properties
file.
management.endpoints.web.exposure.include=health,info,metrics,beans
Spring Boot DevTools is a set of tools that can make the application development process easier. It provides features like automatic restart, live reload, and sensible development-time configuration.
The application.properties
(or application.yml
) file is used to configure a Spring Boot application. It allows you to define properties for various aspects of the application, such as server port, database connection, logging, and more.
application.properties
: The main configuration file for a Spring Boot application.bootstrap.properties
: A special configuration file that is loaded before application.properties
. It's used for configuration that needs to be available early in the application startup process, such as connecting to a configuration server.Spring Profiles provide a way to segregate parts of your application configuration and make it only available in certain environments. You can use the @Profile
annotation to mark beans or configuration classes that should only be loaded for a specific profile.
You can activate a Spring Profile by setting the spring.profiles.active
property in your application.properties
file, or by passing it as a command-line argument.
spring.profiles.active=dev
The @ConfigurationProperties
annotation is used to bind external configuration properties to a Java object. It provides a type-safe way to work with configuration properties.
The @EnableAutoConfiguration
annotation enables Spring Boot's auto-configuration mechanism. It attempts to automatically configure your Spring application based on the jar dependencies that you have added.
The @Transactional
annotation is used to declare that a method or class should be executed within a database transaction. Spring provides a powerful transaction management framework that simplifies the handling of transactions in an application.
Transaction propagation determines how transactions relate to each other. Spring defines the following propagation levels:
REQUIRED
(Default): Supports a current transaction, creates a new one if none exists.SUPPORTS
: Supports a current transaction, executes non-transactionally if none exists.MANDATORY
: Supports a current transaction, throws an exception if none exists.REQUIRES_NEW
: Creates a new transaction, and suspends the current transaction if one exists.NOT_SUPPORTED
: Executes non-transactionally, suspends the current transaction if one exists.NEVER
: Executes non-transactionally, throws an exception if a transaction exists.NESTED
: Executes within a nested transaction if a current transaction exists, otherwise behaves like REQUIRED
.TransactionTemplate
or the PlatformTransactionManager
.JpaRepository
is a Spring Data interface that provides sophisticated CRUD functionality for JPA-based data access layers. It extends the PagingAndSortingRepository
and CrudRepository
interfaces.
CrudRepository
: Provides basic CRUD operations.PagingAndSortingRepository
: Extends CrudRepository
and adds methods for pagination and sorting.JpaRepository
: Extends PagingAndSortingRepository
and adds JPA-specific methods like flush()
and saveAndFlush()
.For more details on Spring JPA and data access, you can read more about it here.
Spring Data can automatically create repository methods based on the method names. For example, a method named findByEmail(String email)
will automatically generate a query to find a user by their email address.
The @Query
annotation is used to provide a custom query for a repository method. This is useful when the method name is not sufficient to generate the desired query.
A projection allows you to selectively retrieve parts of an entity. You can create an interface that defines the properties you want to retrieve, and Spring Data will automatically implement it for you.
Optional
is a container object which may or may not contain a non-null value. Spring Data repositories use Optional
to indicate that a query might not return a result. This helps to avoid NullPointerException
.
The Page
interface is used to represent a page of data. It provides methods to get the content of the page, the page number, the page size, and the total number of elements.
For more details on pagination in Spring Boot, you can read more about it here.
Spring provides a caching abstraction that allows you to transparently apply caching to your methods. It supports various cache providers like EhCache, Caffeine, and Redis.
@EnableCaching
: Enables Spring's caching support.@Cacheable
: Indicates that the result of a method should be cached.@CachePut
: Updates the cache with the result of a method.@CacheEvict
: Removes an entry from the cache.@Cacheable
: The method is only executed if the cache does not contain the requested entry.@CachePut
: The method is always executed, and its result is put into the cache.Spring WebFlux is a reactive web framework that is part of the Spring Framework. It's an alternative to Spring MVC and is designed for building non-blocking, event-driven applications.
Mono
and Flux
are reactive types from the Project Reactor library, which is used by Spring WebFlux.
Mono
: Represents a stream of 0 or 1 elements.Flux
: Represents a stream of 0 to N elements.The @SpringBootTest
annotation is used for integration testing in Spring Boot. It loads the full application context and allows you to test the interaction between different components.
The @MockBean
annotation is used to add a mock object to the Spring application context. It's useful when you want to mock a specific bean in your integration tests.
@Mock
: A Mockito annotation that creates a mock object. It's used for unit testing.@MockBean
: A Spring Boot annotation that adds a mock object to the application context. It's used for integration testing.For more details on Spring Boot integration testing, you can read more about it here.
For more details on building a complete Spring Boot application with MongoDB and S3, you can read more about it here.
SpEL is a powerful expression language that supports querying and manipulating an object graph at runtime. It can be used in XML or annotation-based Spring configurations.
@ResponseBody
: An annotation that indicates that the return value of a method should be written directly to the HTTP response body.ResponseEntity
: A class that represents the entire HTTP response, including the status code, headers, and body. It gives you more control over the response.The @ExceptionHandler
annotation is used to handle specific exceptions in a controller. You can use it to define a custom error response for a particular exception.
@ControllerAdvice
: A specialization of the @Component
annotation which allows to handle exceptions across the whole application in one global handling component.@RestControllerAdvice
: A specialization of @ControllerAdvice
that is used for RESTful services. It's a combination of @ControllerAdvice
and @ResponseBody
.Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, cluster state).
Service discovery is the process of automatically detecting devices and services on a network. In a microservices architecture, it's used to allow services to find and communicate with each other without hardcoding the hostnames and ports.
Spring Cloud Gateway is a project that provides an API Gateway for microservices. It's built on top of Spring WebFlux and provides features like routing, filtering, and circuit breaking.
A circuit breaker is a design pattern used to detect failures and encapsulates the logic of preventing a failure from constantly recurring. In Spring Cloud, you can use the Resilience4j library to implement the circuit breaker pattern.
Spring Cloud Config provides server-side and client-side support for externalized configuration in a distributed system. With the Config Server, you have a central place to manage external properties for applications across all environments.
Spring Cloud Sleuth is a distributed tracing solution for Spring Cloud. It adds unique IDs to each request that flows through the system, which allows you to trace a request across multiple services.
Spring Batch is a lightweight, comprehensive batch framework designed to enable the development of robust batch applications vital for the daily operations of enterprise systems.
A Job
is an entity that encapsulates an entire batch process. A job is composed of one or more Step
s.
A Step
is a domain object that encapsulates an independent, sequential phase of a batch job. Every Job
is composed of one or more Step
s.
The ItemReader
is an abstraction that represents the retrieval of input for a Step
, one item at a time.
The ItemProcessor
is an abstraction that represents the business processing of an item.
The ItemWriter
is an abstraction that represents the output of a Step
, one batch or chunk of items at a time.
Chunk-oriented processing refers to reading the data one item at a time, and creating 'chunks' that will be written out, within a transaction boundary.
Tasklet
: A simple interface that has one method, execute
, which will be called repeatedly until it either returns RepeatStatus.FINISHED
or throws an exception to signal a failure.Chunk
: A Step
that is configured to be chunk-oriented will read and process items in chunks, and then write them out.The @Scheduled
annotation is used to run a task at a scheduled interval. It can be used to run a Spring Batch job at a specific time or interval.
fixedRate
: The time between the start of each execution.fixedDelay
: The time between the end of the previous execution and the start of the next one.BeanFactory
: The root interface for accessing a Spring bean container. It provides basic IoC functionality.ApplicationContext
: A sub-interface of BeanFactory
. It adds more enterprise-specific functionality, such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.The @SpringBootApplication
annotation is a convenience annotation that adds all of the following:
@Configuration
: Tags the class as a source of bean definitions for the application context.@EnableAutoConfiguration
: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.@ComponentScan
: Tells Spring to look for other components, configurations, and services in the specified package, allowing it to find and register the beans.JPA
(Java Persistence API): A specification that describes how to manage relational data in Java applications.Hibernate
: An implementation of the JPA specification. It's an Object-Relational Mapping (ORM) tool that provides a framework for mapping an object-oriented domain model to a relational database.The N+1 selects problem occurs when you fetch a list of entities from the database and then iterate over them, lazily fetching a related entity for each one. This results in one query to fetch the list of entities, and then N additional queries to fetch the related entities.
You can solve the N+1 selects problem by using a JOIN FETCH
clause in your query, or by using a @EntityGraph
annotation to specify which associations should be fetched eagerly.
Eager Fetching
: The related entities are fetched from the database along with the main entity.Lazy Fetching
: The related entities are only fetched from the database when they are accessed for the first time.The @Value
annotation is used to inject values from properties files, system properties, or environment variables into your beans.
@Value
: Used to inject a single value.@ConfigurationProperties
: Used to bind a whole set of properties to a Java object. It's generally more type-safe and convenient for working with multiple properties.RestTemplate
is a synchronous client to perform HTTP requests. It's part of the Spring Framework and provides a simple way to communicate with RESTful web services.
RestClient is the new synchronous client to perform HTTP requests. Now it is preferred over RestTemplate and has got a fluent API like WebClient.
For more details on REST clients in Spring, you can read more about it here.
WebClient
is a non-blocking, reactive client to perform HTTP requests.
The @Async
annotation is used to mark a method as asynchronous. When a method is annotated with @Async
, it will be executed in a separate thread.
You can enable asynchronous processing by using the @EnableAsync
annotation in your configuration class.
For more details on Spring Boot concurrency and async processing, you can read more about it here.
The ApplicationRunner
interface is used to execute some code after the Spring Boot application has started. It provides a run
method that is called just before SpringApplication.run()
completes.
The CommandLineRunner
interface is similar to ApplicationRunner
, but it provides access to the command-line arguments as a string array.
The main difference is the type of arguments they receive. ApplicationRunner
receives an ApplicationArguments
object, while CommandLineRunner
receives a string array.
The @Conditional
annotation is used to indicate that a component is only eligible for registration when all specified conditions match.
@ConditionalOnClass
: The class is loaded if the specified class is on the classpath.@ConditionalOnBean
: The class is loaded if the specified bean is present in the ApplicationContext
.@ConditionalOnProperty
: The class is loaded if the specified property has a certain value.The spring-boot-starter-parent
provides default configuration for your Spring Boot application. It includes dependency management for common libraries and plugins, and it sets up the default Java compiler version.
A fat JAR is a self-contained JAR file that includes all the dependencies required to run an application. Spring Boot creates a fat JAR by default, which makes it easy to run the application as a standalone process.
server.port
: The port on which the main application runs.management.server.port
: The port on which the Actuator endpoints are exposed. It's a good practice to use a different port for management endpoints for security reasons.The @EnableWebMvc
annotation is used to enable Spring MVC configuration. It's typically used in conjunction with a @Configuration
class to customize the Spring MVC setup.
@PathVariable
: Used to extract values from the URI path.@RequestParam
: Used to extract values from the query string.The spring.factories
file is a special file that is used by Spring Boot to load auto-configuration classes. It's located in the META-INF
directory of a Spring Boot starter.
The @Lazy
annotation is used to initialize a bean lazily. By default, Spring creates all singleton beans at startup. If you annotate a bean with @Lazy
, it will only be created when it's first requested.
The spring-boot-maven-plugin
provides several features for Spring Boot applications, including:
The @Entity
annotation is used to mark a Java class as a JPA entity. An entity represents a table in a relational database.
The @Id
annotation is used to specify the primary key of an entity.
The @GeneratedValue
annotation is used to specify how the primary key of an entity should be generated. It can be used with different strategies, such as AUTO
, IDENTITY
, SEQUENCE
, and TABLE
.
Get instant AI-powered summaries of YouTube videos and websites. Save time while enhancing your learning experience.