Spring and Spring Boot Notes
Spring and Spring Boot Notes
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.
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>
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.
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.
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
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.
<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.
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.
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.
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
2. Setter injection — more flexible, mutable objects, injection via setters. Possible to
3. Field injection — fast and convenient, coupling with IoC container. Possible to configure
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
plate codes in the application. Good readability as it is separately present in the code.
The bean must include getter and setter arguments. Otherwise, BeanCreationException will be
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)
because object creation happens before No scope for circular or partial dependency because
Preferred option when properties are less immutable objects (eg: financial processes) are important
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.
this method at runtime and uses the proxy to deliver the new object every time.
| 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) |