0% found this document useful (0 votes)
301 views8 pages

Spring Boot Essentials for Developers

Uploaded by

anand.abhee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
301 views8 pages

Spring Boot Essentials for Developers

Uploaded by

anand.abhee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Spring framework solves the following;

a. Removal of [Link] 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.

[Link]

2. Spring MVC
Dispatcher Servlet - First controller
Handler Mapping - Helps in determining which controller and controller method to call

3. Spring Boot - Spring MVC + Addition benefits:


a. Dependency management - Version is optional for spring framework dependencies,
which is not the case in Spring MVC so in Spring MVC we have to track which all
version of dependency A work with which version of the dependency B.
b. Auto Configuration - No need to separately configure Dispatcher Servlet, AppConfig,
EnablewebMVC, ComponentScan. @SpringBootApplication will do the trick.
c. Embedded Server - In tradition Spring MVC application, we had to build WAR files
which packed application classes, JSP pages, Configuration files, and dependencies
and then deploy this WAR file to a servlet container like Tomcat. In SpringBoot,
Servlet container is already embedded, so no need to do all this stuff.

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.

5. Maven - Project management tool - Build generation tool, dependency resolution,


Documentation, etc.
[Link]

Project Object Model (POM) - Every [Link] 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 -

[Link]

@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 -

[Link]

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.

How Spring boot find these beans?


@ComponentScan(basePackages = "") in main class file, although its part of the
@SpringBootApplication.
@Configuration - Explicit definition of @Bean annotation in @Configuration class.

At what time these bean gets created -


Eagerness - At the start of the application. Singleton Scope are eagerly initialized
Lazy - Created when needed. Beans with scope like Prototypes etc. Also, beans with @Lazy
annotation.

Lifecycle:

8. Dependency Injection

[Link]

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
[Link]
[Link]

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.
[Link]

10. In [Link] we can give multiple values, like [Link]= dev, qa. In this
case, [Link] will be picked but if there are beans with @Profile("dev") and
@Profile("qa"), both will be created.
[Link]

11. Aspect Oriented Programming (AOP)


[Link]

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 [Link]..methodName())"))

2. Within - Matches all method within any class or package


3. @within - matches any method in a calls which has a particular annotation
4. @annotation - matches any method that is annotated with a given annotation
5. Args - matches any method with particular arguments (or parameters)
@Before("args(String, int)")
@Before("args([Link])")
6. @args - matches any method with particular parameters and that parameter class is
annotated with particular annotation.
7. Target - matches any method on a particular instance of a class

Advice - Action which take place @Before or @After or @Around the method execution.

12. @Transactional -

[Link]
[Link]
[Link]

Helps to achieve ACID property.


A (Atomicity) - Ensures all operations within a transaction are completed or entire thing is rollback.
C (Consistency) - Ensures that DB state before and after the transaction is consistent.
I (Isolation) - Ensures that even if multiple transactions are running in parallel, they do not interfere
with each other.
D (Durability) - Ensures that committed transaction will never be lost despite system failure or crash.

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 -
[Link]
[Link]

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.

Condition for @Async to work properly:


1. Different class: @Async annotated method shouldn't be in the same class from which it is
being called, as proxy mechanism is skipped because internal method calls are NOT
INTERCEPTED.
2. Public method: @Async annotated method should be public as AOP interception works only
on Public methods.

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:
[Link]
[Link]

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.

@EnableWebSecurity - When we annotate a configuration class with @EnableWebSecurity, we are


telling Spring to enable Spring Security's web security support. This indicates that you want to
customize the security configuration instead of relying on the default settings. Without this annotation,
Spring Boot will automatically configure security with a basic setup, including form-based
authentication and CSRF protection. Adding @EnableWebSecurity overrides this default behavior.

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.

The @EnableGlobalMethodSecurity(prePostEnabled = true) annotation in Spring Security is used to


enable method-level security for your application.

16. Exception Handling:

[Link]

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.

Common questions

Powered by AI

IoC in Spring resolves the tight coupling between classes/interfaces, adhering to the Dependency Inversion principle of SOLID design. It provides multiple injection methods such as constructor injection, which facilitates immutable object creation and resolves dependencies at object initialization, mitigating issues like unsatisfied or circular dependencies through annotations like @Primary or @Qualifier .

Spring Boot simplifies dependency management by making the version optional for Spring Framework dependencies, unlike traditional Spring MVC, where developers must track and align compatible versions of dependencies manually .

The @Transactional annotation in Spring manages transaction propagation through various strategies like REQUIRED (the method uses an existing parent transaction), REQUIRES_NEW (suspends any existing parent transaction and starts a new one), and SUPPORTS (uses the parent transaction if available). These propagation strategies affect transaction execution by controlling transaction boundaries and enhancing control over transaction workflow, thereby ensuring ACID properties .

When multiple Spring profiles are active, such as 'dev' and 'qa', beans annotated with both profiles are created, which can lead to conflicts if similar beans have conflicting behaviors or configurations. Spring handles this by resolving profiles precedence and creating each profile-specific bean, enabling environments to coexist, though careful configuration management is necessary to avoid unexpected behavior in multi-profile scenarios .

Embedded servers in Spring Boot simplify deployment by eliminating the need for external servlet containers and WAR file packaging. Applications can be executed as standalone JAR files with embedded servlet containers like Tomcat, streamlining the deployment process, and reducing deployment time and complexity .

The removal of web.xml enhances maintainability by eliminating the complex and error-prone manual configuration of servlets and mappings. This is replaced by Java-based configuration and annotations, which are easier to version control, programmatically manage, and refactor in large-scale projects, reducing configuration overhead .

In Spring MVC, @Controller is used for components that return views (such as JSP files), while @RestController is used when responding directly with HTTP response bodies. This distinction allows @RestController to automatically map return values to HTTP responses, streamlining the creation of RESTful APIs .

Maven's POM contributes to effective lifecycle management by standardizing build processes, managing dependencies, and inheriting configurations through a hierarchy of POM files. It automates tasks such as compilation, packaging, and deploying, while ensuring dependency compatibility through convention over configuration, simplifying project management .

AOP in Spring improves code reusability and maintainability by allowing developers to separate cross-cutting concerns like logging and transaction management from business logic. It uses constructs like Pointcut to apply Advice (code execution before/after methods) at specific join points, reducing boilerplate code and enabling modularization of repetitive tasks across the application .

The @Async annotation facilitates asynchronous processing by executing methods in separate threads, thus preventing main thread blockage and improving response time. For @Async to work correctly, the async method must be public and not in the same class as the caller due to AOP proxy limitations; proper exception management with AsyncUncaughtExceptionHandler is also imperative to handle unhandled exceptions effectively .

You might also like