SpringBoot
SpringBoot
a. Removal of web.xml which use to have servlet configuration which was difficult to
maintain for big projects.
b. Introduction to IoC (Dependency Injection) to manage object dependencies.
c. Spring made it easier to manage REST APIs.
https://notebook.zohopublic.in/public/notes/bietvaf4a031eeb7245f19e651a16232e077a
2. Spring MVC
Dispatcher Servlet - First controller
Handler Mapping - Helps in determining which controller and controller method to call
4. JAR and WAR (Java Archive and Web Archive) - Use JAR for standalone application, WAR is
used when we need the complete package for web application consisting of HTML, CSS, JSP
pages, javascript.
Project Object Model (POM) - Every pom.xml is a child of another parent pom and if no <parent> is
specified then maven by-default inherit the configurations from the "Super POM". All models implicitly
inherit from a super-POM.
BUILD PROCESS:
In POM, plugins are like tools that help you perform specific tasks during the build process of your
Java project. Think of them as extra features that make Maven more powerful
6. Annotations -
https://notebook.zohopublic.in/public/notes/bietv0de3bac30fbd41e7b1346bf9243ad3b2
@Controller is used to return the view(.jsp files) unless specified otherwise with @ResponseBody
annotation to mark it as a HTTP response, @RestController return everything as HTTP response by
default.
All APIs are in controller classes as Dispatcher Servlet considers methods in controllers as HTTP
requests/APIs.
@InitBinder can help declaring a method which can do preprocessing for values being passed as
parameters in HTTP requests. @InitBinder is an annotation in Spring Framework used to customize
data binding for web applications. It's particularly useful when you're working with forms and want to
manipulate or format data before it's bound to your model objects.
7. Bean -
https://notebook.zohopublic.in/public/notes/bietv2018487e1de84b009904a4dfeda24def
A java object that is managed by Spring Container/IOC Container. IOC Container contains and
manage all the beans that get created. Two ways to create beans, using @Component and @Bean.
@Component - Follows convention over configuration approach, means spring boot tries to auto
configure based on conventions reducing the need for explicit configuration.
@Bean - We provide the configuration details and tell Spring boot to use it while creating a Bean.
Lifecycle:
8. Dependency Injection
https://notebook.zohopublic.in/public/notes/bietv964a637b52be4a1bbfde8d0309040a79
Solves two problems - Tight coupling between classes/interfaces and Dependency Inversion rule of
SOLID principle.
Different way of Injections:
Field Injection - Cannot be used with immutable fields, Chances of Null point exception
Setter Injection - Cannot be used with immutable fields, difficult to read and maintained
Constructor Injection - Recommended. Dependency get resolved at the time of initialization of the
object itself. Can be used to create immutable object.
Issues -
Circular Dependency - Solved with Refactoring, or @Lazy over @Autowired, or @PostConstruct
Unsatisfied Dependency - Suppose an interface is injected which is implemented by multiple class, so
IOC won't understand which bean to inject. Solved with @Primary annotation on top of any one class,
or by using @Qualifier annotation.
9. Bean Scopes
https://notebook.zohopublic.in/public/notes/bietv379bff087eca47eaa84a3024d7e14b46
https://notebook.zohopublic.in/public/notes/bietv13e5f5aeff684305a86e2d251aa4deed
Singleton - Default scope, Only 1 instance per IOC, Eagerly initialized (means at the time of startup,
object get created)
Prototype - Each time a new object is created, lazily initialized
Request - New Object is created for each HTTP request lazily initialized.
Session - New object for each HTTP session (can have multiple HTTP calls in one session), lazy
initialized
If we have a class which is singleton and has a dependency on a class with scope request, so ideally
it'll fail at startup as the singleton initialization will happen at the startup and when it'll try to resolve its
dependency, it'll find that the other class has scope request and since at startup there's no HTTP
request the initialization of the other class will fail. How to solve this?
Ans - Proxy mode - Create a dummy object an initialize in the singleton class. So actually the other
class object is not created, just a proxy. Write like this - @Scope(value = "request", proxyMode =
ScopedProxyMode.TARGET_CLASS)
@ConditionalOnProperty - Create bean on condition, purpose of this is to not clutter our application at
the startup, meaning creating beans only if condition is satisfied.
https://notebook.zohopublic.in/public/notes/dcr5z97c7e76aa1454ea6a57e1a2dde4f8785
10. In spring.profiles.active we can give multiple values, like spring.profiles.active= dev, qa. In this
case, application-qa.properties will be picked but if there are beans with @Profile("dev") and
@Profile("qa"), both will be created.
https://notebook.zohopublic.in/public/notes/dcr5ze84495de6ad14cadbf5fe38b99b18b9d
It helps to intercept the method invocation, and to perform some task before and after the method. It
helps us in focusing on business logic by handling boilerplate and repetitive code like logging,
transaction management, etc. Improves reusability and maintainability of the code.
Spring-boot-starter-aop dependency.
Pointcut - Tells where an ADVICE should be applied.
Types:
1. Execution - Matches a particular method in a particular class
Wildcards -
(*) : matches any single item
(..) : matches 0 or more item
Ex - @Before("execution(returnType com.packagename.class..methodName())"))
Advice - Action which take place @Before or @After or @Around the method execution.
12. @Transactional -
https://notebook.zohopublic.in/public/notes/dcr5za43213ff940049e4857a26389eb54486
https://notebook.zohopublic.in/public/notes/dcr5z827d4c4d67cf491494f30a7733eeb3e1
https://notebook.zohopublic.in/public/notes/dcr5z613a71d83b66404e8692cfca4790232e
Can be applied at class level and method level. If applied at class level it'll get applied at
all public methods.
Transactional manager in Spring Boot uses AOP internally.
Propagation:
REQUIRED (DEFAULT) - If parent transaction is present then methods inside the parent method
won't create new transaction, rather use the parent one.
REQUIRED_NEW - If parent transaction present and there's a method inside parent method then
suspend the parent transaction for a while and create a new transactions for inside methods and once
those are completed/rollbacked, resume the parent transaction.
SUPPORTS - If parent transaction present then use it else no need of transaction for the child
method.
NOT_SUPPORTED - If parent transaction present and there's a method inside parent method then
suspend the parent transaction for a while and execute the child methods without transaction, resume
the parent transaction.
MANDATORY - If parent transaction present then use it, otherwise throw exception.
NEVER - If parent transaction present then throw exception, if not present then execute the method.
Isolation Level - It tells how the changes made by one transaction are visible to other transactions
running in parallel.
Default isolation level depends on DB, most relational databases uses READ_COMMITTED.
13. @Async -
https://notebook.zohopublic.in/public/notes/dcr5zd72620f1d2574b40a39fe1b017931423
https://notebook.zohopublic.in/public/notes/dcr5z0896f8dfa8ad4dcfafa5d737b2b9c26d
Used to run a method asynchronously in a new thread, without blocking the main thread.
@EnableAsync - Creates a bean for async classes require to process async methods.
How Async creates a new thread? - Spring boot tries to find a defaultExecutor (a thread pool task
executor), if its not present then it uses SimpleAsyncTaskExecutor.
A ThreadPoolTaskExecutor is a SpringBoot object, which is just a wrapper around
Java ThreadPoolExecutor.
If we create a bean of thread pool executer (plain java one) then we must give its name like
@Async("executername") else Spring boot will pick the SimpleAsyncTaskExecutor but if create the
bean for ThreadPoolTaskExecutor (spring wrapper one) then we can simpley write @Async.
Transaction context do not transfer from caller thread to new thread which got created by Async.
Meaning if a transaction method calls an async method then the async method won't come into that
transaction.
@Async method which does not have any return thing then how to handle the exception:
1. Handle within @Async method (not industry standard)
2. There's a default way, spring boot provides a SimpleAsyncUncaughtExceptionHandler which
handles any exception in Async method, which hasn't been handled by us.
3. Custom way - Create a class and implement AsyncUncaughtExceptionHandler and
override handleUncaughtException() method and write your custom logic. Add a config as
well as shown:
14. Custom Interceptors:
https://notebook.zohopublic.in/public/notes/dcr5zfbbb4128be4a406682b6a13ff80ed8fa
https://notebook.zohopublic.in/public/notes/dcr5z502a3a0746974f36b75a50729b691d58
Filter - It intercept the HTTP request and response, before they reach to the servlet.
Servlet(like dispatcher servlet) is a Java class, which accepts the incoming requests, process it and
returns the response. Servlet container (like tomcat) decides which servlet will handle the request, if
there are multiple servlets.
15. Security:
When you add the Spring Security dependency to your project and do not provide any custom
configuration, Spring Security sets up a default security configuration automatically, primarily focused
on user authentication using the UsernamePasswordAuthenticationFilter.
By default, Spring Security does not apply CSRF (Cross-Site Request Forgery) protection to HTTP
GET requests, which aligns with standard web practice.
Spring Security uses a filter chain to process incoming requests. Each request passes through a
series of filters that can perform various security-related tasks, such as authentication, authorization,
and CSRF protection. To customize the security filter chain, we can define a SecurityFilterChain bean
in our configuration class. This bean specifies how to handle different types of requests and can
define authentication mechanisms, access controls, and more.
https://notebook.zohopublic.in/public/notes/9wn9o7260a3af90164c31941f061955edb73d
ExceptionHandlerExceptionResolver, ResponseStatusExceptionResolver,
and DefaultHandlerExceptionResolver are used in Spring to handle exceptions, and they do so in a
specific order. When an exception occurs, Spring checks these resolvers in the following sequence:
ExceptionHandlerExceptionResolver: This resolver looks for methods annotated with
@ExceptionHandler in your controllers or @ControllerAdvice annotated class. If a matching handler is
found for the thrown exception, it processes the request accordingly.
ResponseStatusExceptionResolver: If the first resolver does not handle the exception, this resolver
checks if the exception is annotated with @ResponseStatus. If it is, it generates an HTTP response
with the specified status code.
DefaultHandlerExceptionResolver: Finally, if neither of the first two resolvers handles the exception,
this resolver deals with common Spring exceptions, such
as NoHandlerFoundException, HttpMediaTypeNotSupportedException, etc., returning appropriate
HTTP responses.
Ultimately, all exception goes to DefaultErrorEttributes where proper error response structure with
additional info is created and error response is sent back.
@ExceptionHandler -
The @ExceptionHandler annotation can be used in a controller method to handle specific exceptions
thrown by that controller. The method annotated with @ExceptionHandler can accept several
parameters, including:
HttpServletRequest: This parameter allows access to the request data.
HttpServletResponse: This parameter allows you to manipulate the HTTP response.
Exception: This parameter should match the type of exception you want to handle. If the method is
designed to handle a specific exception, it should be of that type.
If we want to handle multiple exceptions, we can specify them in the @ExceptionHandler annotation.
In this case, the method can still accept
the HttpServletRequest and HttpServletResponse parameters, and the exception parameter can be of
a common parent class (or interface) that encompasses all the specified exceptions. This allows us to
handle a group of related exceptions in a single method.