Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Contents

Spring Bean Life Cycle :................................................................................................................................................2


How Spring Boot Application Works internally ?...............................................................................................................3
What is contextLoaderListner ?........................................................................................................................................6
What are different Contexts (Dealing with context) :.........................................................................................................6
Servlet Context:........................................................................................................................................................6
Application Context:................................................................................................................................................7
Bean Scopes....................................................................................................................................................................8
Annotations :..................................................................................................................................................................... 9
Filter vs Interceptor :..........................................................................................................................................................9
Bean Injections :..............................................................................................................................................................10
Prototype-scoped bean in a singleton-scoped bean......................................................................................................12
....................................................................................................................................................................................... 13
Stereotype Annotations:.................................................................................................................................................16
Spring Bean Life Cycle :

Every object that is under the control of Spring’s ApplicationContext in terms


of creation, orchestration, and destruction is called a Spring Bean.

The most common way to define a Spring bean is using


the @Component annotation

 Aware Interfaces
Spring provides several aware interfaces. These are used to access the Spring Framework infrastructure.
The aware interfaces are largely used within the framework and rarely used by Spring programmers.

You as Spring programmers should be familiar with the following three aware interfaces.
 BeanNameAware: ThesetBeanName() callback of this interface supplies the name of the bean.
 BeanFactoryAware: Provides setBeanFactory(), a callback that supplies the owning factory to the bean
instance.
 ApplicationContextAware: ThesetApplicationContext() method of this interface provides
the ApplicationContext object of this bean.

 Bean Post Processor


Spring provides the BeanPostProcessor interface that gives you the means to tap into the Spring context
lifecycle and interact with beans as they are processed.

How Spring Boot Application Works internally ?


Let’s understand how autoconfiguration works
 We mention the starter pom in the pom.xml and it downloads all the dependent jar automatically.
 In that jar under the following path configuration is present what and when to initialize.

 Inside spring.factories it is mentioned that what to enable and what to disable based on the
@Conditional and @Configuration annotations.
 @Conditional was introduced in spring 4+ before that workaround was profiler.
 Let’s take an example of one starter dependency of Spring Boot Starter JPA

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

It will download the following dependent jars


From spring.factories lets open the JpaRespositoriesAutoConfiguration

 If you see the annotations used it has used @ConditionalOnBean and @ConditionalOnClass.
 If we are using or creating any class with DataSource dependency and Jpa Repository then this class will
configure the JPA repository for us without mentioning anything from US
 Some of the conditions explanation is given below

Now we will understand the how Spring Boot application will kick off our Application
Context.
@Configuration : This annotation is part of the spring core framework. Spring Configuration annotation
indicates that the class has @Bean definition methods. So Spring container can process the class and
generate Spring Beans to be used in the application.

@EnableAutoConfiguration : As discussed earlier it will enable and configure few of the Components
based on the conditions

@ComponentScan : This part of “telling Spring where to search” is called a Component Scan.
Spring is a dependency injection framework. It is all about beans and wiring in dependencies.

The first step of defining Spring Beans is by adding the right annotation - @Component or @Service or
@Repository.

However, Spring does not know about the bean unless it knows where to search for it.

Detailed Explanation Link : https://www.springboottutorial.com/spring-boot-and-component-scan

Now what SpringBootApplication.run do

1. It creates the application context


2. Checks the application type (Reactive, Servlet and None)
3. Registers the annotated class with the context
4. Creates the instance of TomcatEmbeddedServletContainer and adds the context.

https://www.youtube.com/watch?v=qlygg_H1M20

What is contextLoaderListner ?
ContextLoaderListener reads the Spring configuration file (with value given against contextConfigLocation
in web.xml), parses it and loads the singleton bean defined in that config file. Similarly when we want to
load prototype bean, we will use same webapplication context to load it.

Another convenient thing about the  ContextLoaderListener is that it creates


a WebApplicationContext and WebApplicationContext provides access to
the ServletContext via ServletContextAware beans and the getServletContext method.
What are different Contexts (Dealing with context) :

Servlet Context:

It is initialized when an Servlet application is deployed. Servlet Context holds all the configurations
(init-param, context-params etc.) of the whole servlet application.

WebApplicationContext is a web aware application context i.e. it has servlet context information. A
single web application can have multiple WebApplicationContext and each Dispatcher servlet
(which is the front controller of Spring MVC architecture) is associated with a
WebApplicationContext. The webApplicationContext configuration file *-servlet.xml is specific to a
DispatcherServlet. And since a web application can have more than one dispatcher servlet
configured to serve multiple requests, there can be more than one webApplicationContext file per
web application.

Application Context:

It is a Spring specific thing. It is initialized by Spring. It holds all the bean definitions and life-cycle
of the of the beans that is defined inside the spring configuration files. Servlet-Context has no idea
about this things.

Every Spring MVC web application has an applicationContext.xml file which is configured as the
root of context configuration. Spring loads this file and creates an applicationContext for the entire
application. This file is loaded by the ContextLoaderListener which is configured as a context
param in web.xml file. And there will be only one applicationContext per web application.
There are two types of contexts in Spring

1. Spring Parent Context (Application Context / Root Context )


<listener>
<listener-lass>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/service-context.xml,
/WEB-INF/dao-context.xml,
/WEB-INF/was-context.xml,
/WEB-INF/jndi-context.xml,
/WEB-INF/json-context.xml
</param-value>
</context-param>

When spring container startups, it reads all the bean definitions from the configuration files
and creates beans objects and manages life cycle of the beans objects. This configuration
is totally optional.

2. Spring Child Context ( WebApplicationContext / Child Context )

<servlet>
<servlet-name>myWebApplication</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myWebApplication</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>

When spring web application starts it will look for spring bean configuration file
myWebApplication-servlet.xml. It will read all the bean definitions and create and manages the
bean objects life cycle. If parent spring context is available it will merge the child spring context
with the parent spring context. If there is no Spring parent context available the application will
only have the child spring context.

Detailed Explanation : http://www.jcombat.com/spring/applicationcontext-webapplicationcontext


Bean Scopes
1. The Scope of the bean defines the lifecycle and visibility of that bean in the context
2. There are 6 type of bean scopes, it can be defined using @Scope annotation
a. singleton
b. prototype
c. request
d. session
e. application
f. websocket

The last four scopes mentioned request, session, application  and websocket  are only available in a
web-aware application.

Scope Description

singleton (default
Single bean object instance per spring IoC container
)

Opposite to singleton, it produces a new instance each and every time a bean is requested.

You should know that destruction bean lifecycle methods are not


prototype called prototype scoped beans, only initialization callback methods are called. So
as developer, you are responsible for clean up prototype-scoped bean instances and
any resource there hold.

A single instance will be created and available during complete lifecycle of an HTTP request.
Only valid in web-aware Spring ApplicationContext.
request
These instances are destructed as soon as the request is completed.

session A single instance will be created and available during complete lifecycle of an HTTP Session.
Only valid in web-aware Spring ApplicationContext.

A single instance will be created and available during complete lifecycle of ServletContext.
Only valid in web-aware Spring ApplicationContext.

In application scope, container creates one instance per web application runtime. It is almost
similar to singleton scope, with only two differences i.e.
application 1. application scoped bean is singleton per ServletContext,
whereas singleton scoped bean is singleton
per ApplicationContext. Please note that there can be multiple
application contexts for single application.

A single instance will be created and available during complete lifecycle of WebSocket.
websocket
Only valid in web-aware Spring ApplicationContext.

Annotations :

Filter vs Interceptor :
Interceptor runs between requests.
Interceptor is Spring specific Concept and Filter is a servlet API.

Filters are used in the webcontext and can’t run outside the webcontext.
Interceptors can be used anywhere.

Filter can be used for authentication of WebPages


For Security layer in business logic or logging interceptor can be used.

Creating the Interceptor in Spring Boot Application


Extends HandlerInterceptorAdaptor to create the interceptor class
Create the registerer class which will implement the WebMvcConfigurer

This class will register all the interceptors which we will use as interceptors.

Interceptor Class :
Filter works only in J2EE web applications, you can not use outside of the application
servers, Interceptors can work in different components and not depends on the web layer, in
summary interceptor have a wide field than filters. If you are planning to move some component
outside the container, you should consider use interceptors.

Filters work more in the request/response domain, in the other hand interceptor act more in the
method execution domain.

If you need to do something that could affect the request or response to your application such as
logging, security, audit, or you will affect the data coming on them, your option is filter, don't forget
the plug ability that those provides.

Bean Injections :

1. Constructor injection — good, reliable and immutable, inject via one of the

constructors. Possible to configure in: XML, XML+Annotations, Java, Java + Annotations.

2. Setter injection — more flexible, mutable objects, injection via setters. Possible to

configure in: XML, XML+Annotations, Java, Java + Annotations.

3. Field injection — fast and convenient, coupling with IoC container. Possible to configure

in XML+Annotations, Java + Annotations.

4. Lookup Method injection — totally different from others, used for injection

dependency of smaller scope. Possible to configure in: XML, XML+Annotations, Java, Java

+ Annotations.
SETTER DI CONSTRUCTOR DI

Poor readability as it adds a lot of boiler

plate codes in the application. Good readability as it is separately present in the code.

The bean class must declare a matching constructor with

The bean must include getter and setter arguments. Otherwise, BeanCreationException will be

methods for the properties. thrown.

Requires addition of @Autowired Best in the case of loose coupling with the DI container as it

annotation, above the setter in the code is not even required to add @Autowired annotation in the

and hence, it increases the coupling code.(Implicit constructor injections for single constructor

between the class and the DI container. scenarios after spring 4.0)

Circular dependencies or partial

dependencies result with Setter DI

because object creation happens before No scope for circular or partial dependency because

the injections. dependencies are resolved before object creation itself.

Preferred option when properties on the bean are more and

Preferred option when properties are less immutable objects (eg: financial processes) are important

and mutable objects can be created. for application.

Prototype-scoped bean in a singleton-scoped bean.


Since singletons are created (and then injected) during context creation it’s the only time the Spring
context is accessed and thus prototype-scoped beans are injected only once, thus defeating their
purpose.
Problem :

Now inside the singleton service we have injected the prototype service.
Now prototype will return the current date time when the object is initialized.

Output :

Now if you see the above output the date is returning same output. It means only one object is created.

It is acting as a singleton.
Solution 1 : Using Application Context

Now if you see the above code then we have used the application context to get bean every time, so

this solution will violate the IOC principle and it is good to use in proxy classes.

Now if you see it has generated the two objects as per called.

Solution 2 : Using Method Injection i.e @Lookup


We have used the lookup annotation, we have returned null but it won’t matter since spring will override

this method at runtime and uses the proxy to deliver the new object every time.

Solution 3 : Using Injex Provider

Solution 4 : Using Object Factory


Stereotype Annotations:
Spring @Component, @Repository, @Service and @Controller

| Annotation | Meaning                                             |
+------------+-----------------------------------------------------+
| @Component | generic stereotype for any Spring-managed component |
| @Repository | stereotype for persistence layer                    |
| @Service   | stereotype for service layer                        |
| @Controller | stereotype for presentation layer (spring-mvc)      |

You might also like