What is Spring
The most popular application development framework for enterprise Java
What is Spring Framework
An open source java platform.
Framework of Frameworks: supports other frameworks like hibernate
It has modules: IoC, AOP
Advantages of Spring
●Predefined Templates – for JDBC, JPA ; save a lot of code
●Lightweight – no inherit or implement of class, POJO implementation
●Loosely Coupling – dependency injection
●Easy to Test – dependency injection
●Fast Development – dependency injection
●Powerful Abstraction
●Declarative Support – for validation, formatting
Dependency Injection
●Dependency :
object A depends on object B, if object A needs object B to execute correctly.
●Tightly Coupled ☹
●If object B has other dependencies, A need to know about them too.
●If change of implementation, need to change the code.
●Loosely Coupled ☺
●Reusable of code
●Easy to test
●Injection :
adding something external to the flow.
●Glue 2 classes together while keeping them independent.
●Two types of Dependency Injection in Spring
●Constructor based
●Setter based
Inversion of Control (IoC)
●A design pattern, removes dependency from code, makes the code loosely coupled.
●No modification of code if logic is moved to a new environment.
Spring IoC Container
●In Spring Framework, IOC container is responsible to inject the dependency.
●Provide metadata to the IOC container either by XML file or annotation.
Two types of IoC Containers in Spring
●BeanFactory
●ApplicationContext
What is a Bean
●The objects that are instantiated, assembled or managed by the Spring IOC container.
●Created with configuration metadata supplied to the container in the form of XML.
●declare bean using <bean> element and inject <bean> with using
<constructor-arg> and <property> elements in xml configuration file.
●Another way of bean configuration is using annotations.
Spring as a Container
● Spring is a Container of Beans/a Factory of Beans, dependency injection is possible.
● What is a container?
● Tomcat Servlet Container
● All servlets are configured in xml and supply the classes.
● Tomcat creates servlets required by reading xml
● Similarly;
● Spring is a container of beans, POJOs (objects) are contained in spring
container, supplied as requested by others.
● All objects are managed by Spring Container
● Handles the instantiation
● Handles whole lifecycle
● Handles destruction of objects
Bean Factory
● Factory Pattern
● Instead of creating a new object, make a call to Object Factory which creates new objects according to some configuration and hands it over to the requested object.
● ApplicationContext
● BeanFactory with additional functionalities.
● When defining ApplicationContext, reads Spring XML and initializes available beans itself without any call of getBean
● When another object call getBean, ApplicationContext handsover the objects that already been initialized.
● Advantage
● Spring bean is created in the Bean Factory
● Spring has the handle of the Bean
● Spring acts as a container of this newly created bean
Bean Life Cycle
● Spring container is responsible for managing the lifecycle of beans created through it.
● When a bean is instantiated, it may be required to perform some initialization to get it into a usable state.
● Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.
● Lifecycle consists of call back methods :
1. post initialization call back methods
2. pre destruction call back methods
● Spring Framework provides 4 ways of controlling lifecycle events of bean :
1. InitializingBean and DisposableBean callback interfaces
2. custom init() and destroy() methods in bean configuration file
3. @PostConstruct and @PreDestroy annotations
4. Other Aware interfaces for specific behavior
InitializingBean and DisposableBean callback interfaces with single methods in each
org.springframework.beans.factory
InitializingBean : void afterPropertiesSet() throws Exception;
allows a bean to perform initialization work after all necessary properties on the bean have been set by the container.
DisposableBean : void distroy() throws Exception;
allows a bean to get a callback when the container containing it is destroyed.
custom init() and destroy() methods in bean configuration file
●The previous one is not a preferable way to initialize the bean because it tightly couple your bean class with spring container.
●A better approach is to use “init-method” attribute in bean definition in applicationContext.xml file.
●The default init and destroy methods in bean configuration file can be defined in two ways:
●Bean local definition applicable to a single bean
<beans>
<bean id="beanC" class="com.virtusa.model.BeanC" init-method="customInit" destroy-method="customDestroy"/>
</beans>
●Global definition applicable to all beans defined in beans context
<beans default-init-method="customInit" default-destroy-method="customDestroy">
<bean id="beanA" class="com.virtusa.model.BeanA“/>
<bean id="beanB" class="com.virtusa.model.BeanB“/>
</beans>
@PostConstruct and @PreDestroy annotations
●Spring 2.5 onwards, you can use annotations also for specifying life cycle methods using @PostConstruct and @PreDestroy annotations.
@PostConstruct annotated method
will be invoked after the bean has been constructed
using default constructor and just before it’s instance
is returned to requesting object.
@PreDestroy annotated method
is called just before the bean is about be destroyed
inside bean container.
this post processor will do the validation at the back end :
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
Other aware interfaces for specific behavior
●Spring offers a range of Aware interfaces
that allow beans to indicate to the container that they require a certain
infrastructure dependency. Each interface will require you to implement a
method to inject the dependency in bean.
● These interfaces can be summarized as :
●ApplicationContextAware
●ApplicationEventPublisherAware
●BeanClassLoaderAware
●BeanFactoryAware
●BeanNameAware
●BootstrapContextAware
●LoadTimeWeaverAware
●MessageSourceAware
●NotificationPublisherAware
●PortletConfigAware
●PortletContextAware
●ResourceLoaderAware
●ServletConfigAware
●ServletContextAware
Bean Scope
2
basic bean scopes :
● Singleton
– only once per Spring container
● when
ApplicationContext initialized, all Singleton beans are
initialized.
● Prototype
– new bean created with every request or reference
● spring
waits for a getBean to happen, then it initializes the
prototype, a new reference.
● ex:
Point0 , defined as a prototype bean, if it is referenced in two other beans,
each of those beans would have different instance of that Point0 object.
other bean scopes :
Web-aware
scopes
Spring
tights to web applications, can use to create servlet beans, tights to servlet
API. Spring knows when is a new request, when is a new session. Can tie the
beans scope to request and the session.
● Request
- new bean per servlet request
● call
getBean inside a new request scope, a new bean
is created, but in same request scope, same bean is going to be used.
● Session
- new bean per session
● if
one user access a single session, no matter how many getBean calls happen, only one bean is returned,
if one user with new session, a new bean is created.
● Global
Session - new bean per global HTTP session (portlet context)
● if
have a global session and an individual portlet sessions, can tie a bean into a portlet context.
Bean Auto-wiring in Spring
● This feature of spring framework enables
injecting object dependency implicitly.
● Work with reference only, cannot use to inject primitive or string values.
● The Spring
Container can autowire relationships between collaborating
beans without using <constructor-arg>
and <property> elements which used to skip some of the configurations.
● First look
for bean type to be injected or if there are multiple beans of same type then looking for a matching name or a clue.
● Auto-Wiring modes
● no : no autowiring by default (autowiring is OFF) ;
explicitely set the dependencies using tags in bean
definitions
● byName : inject the object dependency based on bean
name, property
name = bean name ; internally calls
setter
● byType : inject the object dependency based on bean
type,
property name != bean
name ;
internally calls setter
● byConstructor :
injects the dependency by calling the constructor of the class,
(constructor with larger no of parameters)
● Autodetect :
Spring first
tries to wire using autowire by constructor,
if
it does not work, Spring tries to autowire by byType.
Annotations
●Used
to provide bean configuration , configure the dependency injection
●@Required
●applies
to bean property setter methods.
●@Autowired
●can
apply to bean property setter
methods, non-setter methods, constructor and properties.
●@Qualifier
●along
with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.
●JSR-250
Annotations
●Spring
supports JSR-250 based
annotations which include @Resource, @PostConstruct and @PreDestroy annotations.
●Post
processor
Post Processor
Spring MVC
Aspect Oriented Programming (AOP)
●Breaking
down the program logic into distinct parts, concerns.
cross-cutting
concerns : functions that span multiple points of
an application.
●Remove
these common functionalities and create an Aspect.
aspect : the unit of modularity (class or
object : OOP)
examples
of aspects : logging, caching, auditing, security
DI
helps decouple your application objects from each other.
AOP
helps decouple cross-cutting concerns from the objects that they affect.
AOP
implementations :
Spring AOP, AspectJ, JBoss AOP
AOP Concepts and Terminology
●Aspect :
A module which has a set of APIs
providing cross-cutting requirements.
●Join Point :
This represents
a point in your application where you can plug-in AOP aspect.
●Advice :
The actual action to be taken by the aspect either before or after the method
execution.
●Before
Advice : Run advice before the a method execution.
●After
Returning Advice : Run advice after the a method execution
regardless of its outcome.
●After
Throwing Advice : Run advice after the a method execution
only if method completes successfully.
●After
(finally) Advice : Run advice after the a method execution
only if method exits by throwing an exception.
●Around
Advice : Run advice before and after the advised
method is invoked.
●Pointcut :
A set of one or more join points where an advice should be executed.
●Introduction : Allows
you to add new methods or
attributes to existing classes.
●Target Object : The object being advised by one or more
aspects, this object will always be a proxied object. (advised object)
●Intercepter :
An aspect that contains only one
advice.
●AOP Proxy :
Used to
implement aspect contracts, created by AOP framework. It will be a JDK dynamic proxy or
CGLIB proxy
in spring framework.
●Weaving :
The process of linking aspects with
other application types or objects to create an advised object.
This can be done at compile time, load time, or at runtime.
Spring AOP
Spring AspectJ AOP implementation
1) By annotation
@Aspect declares the class as aspect.
@Pointcut declares the pointcut expression.
To define advice :-
@Before declares the before advice. It is applied before calling the actual method.
@After declares the after advice. It is applied after calling the actual method and before returning result.
@AfterReturning declares the after returning advice. It is applied after calling the actual method and before returning result. But you can get the result value in the advice.
@Around declares the around advice. It is applied before and after calling the actual method.
@AfterThrowing declares the throws advice. It is applied if actual method throws exception.
2) By XML configuration (schema
based)
To define advice :-
aop:before applied
before calling the actual business logic method.
aop:
after applied
after calling the actual business logic method.
aop:after-returning applied
after calling the actual business logic method. It can be used to intercept the
return value in advice.
aop:around applied
before and after calling the actual business logic method.
aop:after-throwing applied
if actual business logic method throws exception.
******************************************************************************************