0% found this document useful (0 votes)
32 views54 pages

Workshop 1

Uploaded by

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

Workshop 1

Uploaded by

Surendra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 54

Installation and Configuration

Download following applications and packages and follow the instructions accordingly.

1. Java Software Development Kit

<Download Source>:

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-
2133151.html

Set JAVA_HOME environment variable to directory C:\Program Files\Java\


jdk1.8.0_65

Set PATH environment variable to directory C:\Program Files\Java\jdk1.8.0_65\


bin

Set classpath environment variable to directory C:\Program Files\Java\


jdk1.8.0_65\bin

Assuming that JDKS has been installed on the directory named C:\Program
Files\Java\jdk1.8.0_65

2. Eclipse IDE

<Download Source>:
http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/
release/mars/1/eclipse-java-mars-1-win32.zip

Extract anywhere above zip file and create a shortcut for eclipse.exe fie and keep
the shortcut file on your desktop.

3. Spring Framework

<Download Source>:

http://repo.spring.io/release/org/springframework/spring/4.2.2.RELEASE/spring-
framework-4.2.2.RELEASE-dist.zip

Extract anywhere above zip file and set the path of lib directory in classpath
environment variable.
4. Apache Common Logging API

<Download Source>:

http://www.us.apache.org/dist//commons/logging/binaries/commons-logging-1.2-
bin.zip

Extract anywhere above zip file and set the path of commons-logging-1.2.jar file
in classpath environment variable.

Note: In order to setup environment variable, Right Click on MyComputer->


Click on Properties-> Click on Advanced System Settings-> Click on
Advanced Tab-> Click on Environment Variable button located at the
bottom.

Developing a first Spring Application.

1. Create New Project

 Click on File-> New-> Java Project and create a new Java Project

 Right click on project name and click on Build Path-> Configure Build
Path

- Click on Libraries Tab and Click on Add External Jars button and
add all RELEASE jar files from spring libs folder except javadoc
and sources jar files. Similarly, for logging, add commons-logging-
1.2.jar files from commons-logging-1.2 folder.

2. Crate Package

- Right Click on src folder and create new package named


mypro.lab1

- Right click mypro.lab1 package and create a file named


MyBean.java

- Right click mypro.lab1 package and create a file named


MyContainer.java

- Right click on src folder and create a bean file named Beans.xml

- Paste following lines of source code on MyBean.java file


- Paste Following lines of Source code on MyContainer.java file

- Paste following lines of code on Beans.xml file.


3. Highlight or open MyContainer.java file Run the application by pressing
Ctrl+F11 key.

Starting the Container

The IOC Container is also called as bean factory. IOC Container is started using the
following code:

Using beans from the Factory

Once the bean factory application context has been loaded, desired beans from
BeanFactory is accessed using the following lines of code:

Init() and cleanup() methods

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.In above example, init() method is called
during the bean initialization time after properties values are set-up and cleanup()
method is called after the context.close().The init-method attribute in a bean tag
specifies a method that is to be called on the bean immediately upon instantiation.
Similarly, destroy-method specifies a method that is called just before a bean is
removed from the container.

POJO Classes

POJO stands for Plain Old Java Object, which is an ordinary lightweight Java object not
bound by any special restriction other that those forced by the Java Language
Specification i.e. POJO should not have to extend prespecified classes, implement
prespecified interfaces and contain prespecified annotations. In our example above,
MyBean is POJO.

Spring Bean

A Spring bean is basically an object managed by Spring. More specifically, it is an


object that is instantiated, configured and otherwise managed by a Spring Framework
container. Spring beans are defined in a Spring configuration file (or, more recently, by
using annotations), instantiated by the Spring container, and then injected into your
application.
Spring Ecosystem
We can do web programming in Java without using spring. Spring is a framework. It
helps to organize web applications properly.

Spring Architecture or Ecosystem comprises of following 5 different layers:

- Data Access/Integration

- Web

- Aspect

- Core

- Test

JDBC: It provides APIs for Java application to talk to underlying RDBMS.

ORM: We map our POJOs with relations in RDBMS. Bean from Java applications will
not talk to RDBMS directly rather will be talking to POJOs. ORM uses JPA internally for
persistence. There are various ORM tools available like Hibernate and iBatis.
OXM: Object to XML mapping. It has two phases. Marshalling (Convert XML document
to Object) and Un-Marshalling( Opposite of Marshalling). It supports technologies like
JAXB.

JMS: It supports synchronous (Cell Phone call) and asynchronous (SMS)

Transaction: It has to follow ACID rules.

Web layer has components like Web, Servlet, Portlet and Strut Modules. Web
Component will initialize IoC Container using servlet listener.

AOP: It allows to define interceptors and point-cuts to separate them as required.

Aspects: This module helps to integrate another AOP framework like AspectJ.

Instrumentation: It is the ability to monitor the level of products performance to


diagnose the errors and trace performance.

Testing: Supports to test spring modules using JUnit framework.

Spring core layer has components such as core, Beans, Context and Expression
Language

Core: It has DI and IOC features

Beans: It implements beanfactory interface( IOC container offered by Spring) through


factory pattern.

Context: It is used for ApplicationContext( It is also IOC Container). It uses Core and
Beans module.

Expression Language: It is used for querying and manipulating objects at runtime.


When we have JSP view, and then if we want to fetch the value of bean, then EL is
used.

Java Frameworks
Following are the most commonly used Java Frameworks:

- Hibernate: Database Access Mechanism( Instead of writing SQL query to


communicate with underlying relation, our app communicate POJO)

- Struts: Web Layer

- EJBs: Services like transactions, security and messaging

- Log4J: Logging
Inversion of Control and Dependency Injection
 If you have one Java Object that depends on another, you can inject second
object into the first using XML file. Instead of creating an object in a class which
requires it, Container injects the object into the class which requires it. This is
called dependency injection.

 Dependency injection brings loose coupling among objects. Loose coupling


makes Unit Testing and Integration Testing much easier thereby helping to build
stable software product and software maintainability will also be easier.

 Business logic and dependency (object creation) should be isolated or


abstracted. If classes are tightly coupled, then we need to test the dependent
code as well. Mockito and Easy mocks are mocking frameworks which helps to
create mock object for JUnit Testing .

 Dependency Injection makes it possible for Inversion of Control to happen i.e.


Inversion of Control is done through Dependency Injection. Normally, when a
class requires an object, it has to call a method that returns the desired object.
However, instead of calling to get desired object, control is reversed i.e. the
desired object is injected into the class that requires it by the IOC container
based on the configuration in XML file automatically and the principle is called
Inversion of Control. Here, object creation is out-sourced to a third party called
IOC Container. IOC Container is responsible for identifying the dependencies
associated with each bean and inject those dependencies when object is
needed.

 Mock objects are dummy objects, we need not have to initialize data members of
such objects, neither have to call any methods or constructor of it.
 In Spring, it is only the IOC Container that can create objects or beans and inject
it onto the object that requires it.

 JAVA CODE Which will create a spring bean container which will read the xml
and instantiate bean object

 We will configure beans in XML file and we can get bean from XML file which will
be injected all its dependencies

Bean Container
Bean container that can instantiate bean and we can later fetch beans from the
container as a plain java object. Spring bean container will read the xml and instantiate
bean object

There are different types of IOC container for e.g. BeanFactory Container and
ApplicationContext Container.

a) Spring BeanFactory Container: It is the basic container. All other possible


classes that acts as containers implement BeanFactory. It is the root
container that loads all the beans and provides dependency injection to
enterprise applications. It is only used for Applets. It is not mostly commonly
used. ApplicationContext Container is most commonly used as a defacto IOC
container.

There will be an XML file and in that XML file there will be so many tags like
<bean>. Here <bean> tag corresponds to configuration related to for e.g.
class called user. BeanFactory as an interface has different implementation.
One of the implementation consumes that XML file. It goes through that XML
file. It identifies what are the beans those were listed in that XML file and it
will create objects related to all those beans and if any of those beans have
dependencies with the other beans listed in that XML document, it will inject
those. Source for those containers will be either from XML document or
annotation driven.

b) Spring ApplicationContext Container: It is an advanced container that


extends BeanFactory container with various enterprise-level features like
Internationalization. It is widely used as a container that extends BeanFactory
container with various enterprise level features.

 Objects created by the container are called managed objects or beans. Beans
are nothing but objects created by container. Beans are also called managed
objects because objects created by container will have a life cycle and the entire
control on that bean will be through the container. The Container can be
configured by loading XML files or annotations. IOC Container helps to configure
and manage Java Objects. The Container is responsible for managing object
lifecycle of specific objects; creating these objects, calling their initializing
methods and configuring these objects by wiring(injecting or associating) them
together.

IOC Features: Consume configuration files like XML and by using instance of any of
these we can create the beans configured in the configuration file. IOC Container goes
through the XML file, identifies the beans and it identifies the dependencies, it creates
all beans and it injects the dependencies when.

Object Coupling problem

If two objects are tightly coupled, then we will have following problems:

Resolution of Problem

The above problem can be resolved using Factory pattern. Factory pattern abstracts
object creation.
Bean Life Cycle

Instantiate a bean by calling its constructor. Populating properties means mapping the
arguments in constructor with one that is supplied. Third one is dependency injection
either through constructor or through setter method. Init method is invoked as soon as
constructor is initialized. In this way, bean is ready to use. At last, when container is
shut down, there will be destroy method associated with bean; which gets called the
moment container is shut down. Both Constructors can deal with XML and annotation
i.e. declarative and programmatic.

Application Context

Spring comes with several flavors of application context i.e. ApplicationContext is an


interface and following are various implementations of it. Based on the need, we will go
for one of the implementation.

 ClassPathXmlApplicationContext: Loads context definition from an XML file


located in classpath, treating context definition files as classpath resources.

 FileSystemXmlApplicationContext: Loads context (i.e. XML file) definition from


an XML file in the file system.
 XmlWebApplicationContext: Loads context definitions from an XML file
contained within a web application.

 AnnotationConfigApplicationContext: Creates context by loading classes


annotated with pre-defined annotations.

 AnnotationConfigWebApplicationContext: Creates the web application


context by loading classes annotated with pre-defined annotations in the Web
Application.

Spring Configuration

Following are three different ways to provide configuration metadata to spring


container.

 XML based configuration file

 Annotation based Configuration file

 Java based configuration file .

Note: Maven is a build management tool or project management tool. Maven


comes along with eclipse Luna version .Bean, Core and Context are required to
run a basic spring application. First, create a bean class then XML file and then
IOC Container Class i.e. ApplicationContext.

XML configuration for Bean

 Spring beans can be configured with any name and can be stored anywhere in
the classpath
 In above XML file, we have defined a MyBean bean with the id myBean. For this
bean, we have set its message property to "MyFirstPro". We can define any
number of beans and name XML file with any name.

Attributes to bean Tag

There are many attributes that can be set while defining a bean in a bean
configuration file. Following are few of them:

Dependency Configuration based on depends-on

depends-on attribute is part of bean tag. Bean specified by depends-on attribute is


loaded before the actual bean is instantiated. The depends-on attribute can explicitly
force one or more beans to be initialized before the bean using this element is
initialized. In essence, if some bean would want to use some of the resources or
data in the other bean which can be accessed only if that (second) bean has been
initialized.

Example: We have three beans A, B, C. A depends on B and B depends on C.


Then, C is initialized first, then B and then C.
Dependency Injection Types:

There are following two ways to perform dependency Injection.

 Setter Method Dependency Injection: In this type of DI, the required bean is
injected through setter method for that bean. Container is able to set the values
in the bean.

In the following example, we will inject the required bean through the setter
method. It is to be noted that we have defined setCar () in the User class.

Example:
In following example, class User is dependent on class Car. Instead of creating
an object of car in User class, we inject object of Car class through the setter
method of class User. If we have a closer look at the Application Context File
(lab2.xml); the ref attribute of bean with an id equals to user injects dependent
object i.e. car in the User class.

And the corresponding configuration file is:


 Constructor Based Dependency Injection: In this type of DI, the required bean
is injected through the constructor argument. Container uses the respective
constructor to inject the values.

In the following class Person bean is dependent on Car bean. Car bean is
injected into Person bean through Person Constructor as shown below:
Video Tutorial Reference:
https://www.youtube.com/watch?v=-weKK-
oNuhA&list=PL9ooVrP1hQOEfi91PCFQMawtBJrPpir7y&index=1&feature=iv&src
_vid=WgCKVYJRccI&annotation_id=annotation_1509874713

Autowiring
Wiring means injecting dependencies. Autowiring means automatically injecting
dependencies. Spring can automatically resolve dependencies (or automatically inject
dependencies) using Autowiring. Spring offers Autowiring features that helps cut down
the amount of xml configuration that developers have to write. Spring offers following
types of Autowiring.

 Byname: Spring container looks at the beans on which auto-wire attribute is set
to be byName in the XML configuration file. Based on the name of a property, a
bean with the same name will be injected into this property if it exists.
The test class is:
In above example, bean configuration file specifies autowire to be byname for Student
bean, hence if Student bean is dependent in any other bean( in our case Hostel bean
whose id as per bean configuration file is hostel), then dependent bean ( Hostel bean
whose id is hostel) will be injected onto Student bean based on bean property name of
Hostel in Student bean class (which is hostel) automatically without writing dependency
injection code at all on bean configuration file for student bean. In other words, since
autowiring mode is set to be byname, as soon as IOC Container finds dependent bean
whose instance or property name is hostel, it looks for a bean with an id of hostel, and
as such bean exists, it will inject Hostel bean into the student bean without specifying
dependency injection code in the bean configuration file( i.e. without specifying mapping
information in the bean configuration file with ref tag).

If we want to perform dependency injection on Student class without autowiring, then


following should be our bean configuration file.

 byType: It specifies auto-wiring by property type not by name. Spring container


reads the XML configuration file and for the beans on which autowire attribute is
set to byType, it finds and inject that bean according to type match. Type means
class type. For e.g. if a class is Employee, then its type is Employee. In above
example Hostel hostel, hostel is property name and Hostel is property type.
Autowiring will be done based on the property type available.
 Constructor: If a bean definition is set to autowire by constructor in configuration
file, then Spring container tries to match and wire its constructor argument with
exactly one of the beans whose type matches with type of constructor argument.

Note: By default, spring bean auto wiring is turned off. Spring bean autowire default
value is "default" i.e. no autowiring is to be performed. It will make beans un-available
for auto-wiring. It means no beans should be autowired unless they are individually
configured for autowiring with the autowire attribute. Autowire = "no" also have the same
behavior. If autowiring is set to no, then we have to inject dependency using "ref"
attribute.
Autowiring Limitations:

 Wiring information may not be available to tools that may generate


documentation from a Spring container.

 Multiple bean definitions within the container may match the type specified by the
setter method or constructor argument to be autowired.

 Autowiring is less exact than explicit wiring. If there are several beans of a
particular type exist, a no unique bean exception occurs.

 Both <property> and <constructor-arg> tags always override autowiring.

We can apply annotation to methods with multiple names and/or multiple arguments.
We can apply @Autowired to constructors and fields as well.

By Default, the autowiring fails whenever zero candidate beans are available; the
default behavior is to treat annotated methods, constructors and fields as indicating
required dependencies. This behavior can be changed as follows

@Autowired=false

Because autowiring by type may lead to multiple candidates, it is often necessary to


have more control over the selection process. One way to accomplish this is with
Spring's @Qualifier annotation.

Bean Inheritance(Reusing bean Definitions)


Bean Inheritance is implemented in bean configuration XML file. A child bean definition
inherits configuration, attributes and properties from a parent bean. The child definition
can override some values, or add others, as needed. Using parent or child definition can
save a lot of typing that developers have to do otherwise.

The parent attribute can be used in the child bean definition inside the bean element
that will indicate the parent bean. Thus, the child bean can use the parent bean’s values
and override them. Another way of bean inheritance is by using the abstract attribute to
the parent bean definition, inside the bean element. In this way, the parent bean is a
template that cannot be instantiated alone, but can be used by child beans and its
values can also be overridden.
In above example, dog bean inherits properties of parent bean Animal. Hence, dog
bean overrides name and colour property whereas inherits or can access height
property of animal.

Following is the output of above program:

Inheritance with abstract

In above example, if we want to use animal bean as a template and not to instantiate it,
but only allow child bean to extend it, then we can set abstract=true in the bean element
as shown below.

In above example, we cannot get Object of Animal Bean from Bean Factory i.e.

If we try to do so, we will get following error.

We can get object of only Cat bean from Bean Factory.

Note: While using spring for dependency injection, it is a good practice to use
interfaces for referencing dependencies.
Annotation Based Container Configuration
Instead of injecting dependency by configuring XML file, We can do bean configuration
into the component classes itself by using annotations on the relevant class, method or
field declaration. If we use both annotation and XML configuration, then XML
configuration will override because annotation injection is performed first and then XML
configuration will be injected later. Since annotation based configuration is turned off by
default, we have to turn it on by entering <context:annotation-config/> into spring
XML file.

Some of the core annotations that we use frequently are:

SN Annotation Application Areas Description

1 @Autowired Field, Methods, Declares a field, constructor or setter methods to


Constructors be autowired by type. Items associated with
@Autowired should not be public.

2 @Qualifier Field, Parameter, Guides autowiring to be performed by means


Type other than by type.

3 @Required Setter Methods Specifies that a particular property must be


injected else the configuration will fail.

4 @value Fields Used to specify field for variable

5 @Scope Type Specifies scope of a bean. The possible scope


values are singleton, prototype, request, session
or some custom scope

6 @Configurable Type Used to inject resources in the objects created


using the new operator.

7 @Order Field, Method, Defines ordering


Type

8 @Resource Field, Methods, Performs autowiring by name.


Constructors

9 @PostConstruct Methods Used to call a method during initialization of


bean just after being properties were set.

10 @PreDestroy Methods Used to call a method just before closing the


bean.
 In this way, we learned the @value annotation. @value annotation specifies
default property value for a property variable.

 @Required Annotation: We must have to supply property value, it is


mandatory; otherwise Bean Initialization exception could occur.

 @Autowired annotation performs autowiring by name; whereas @Resource


performs autowiring by name. @Autowired annotation tries to find a bean of type
Car in the spring context and will inject the same. @Resource annotation tries to
find a bean with name "toyota" and will inject the same.

 Since in our XML file, we have declared two beans of same type Car i.e. toyota
and suzuki.

 Since @Autowired annotation wires beans by type, its going to throw an


exception saying "failed to inject bean of type Car because two beans of same
type exist and it doesnt know which bean to inject". So to help Spring get out of
this confusion, we use another type of annotaion i.e. @Qualifier. This Spring
annotation will try to inject a Car type bean whose qualifier value is "obj2".

 @PostConstruct and @PreDestroy annotations are used When we want to have


a init method i.e a method called just after the bean is initialized or destroy
method i.e a method which is called before destroying/deinitializing the beans
respectively.

 To force Spring to produce a new bean instance each time one is needed, we
declare the bean's scope attribute to be prototype. Similar way if we want Spring
to return the same bean instance each time one is needed, we should declare
the bean's scope attribute to be singleton. The spring framework supports
following five scopes.

Scope Description
This scopes the bean definition to a single instance per Spring IoC container
singleton
(default).
prototype This scopes a single bean definition to have any number of object instances.
This scopes a bean definition to an HTTP request. Only valid in the context of
request
a web-aware Spring ApplicationContext.
This scopes a bean definition to an HTTP session. Only valid in the context of
session
a web-aware Spring ApplicationContext.
This scopes a bean definition to a global HTTP session. Only valid in the
global-session
context of a web-aware Spring ApplicationContext.
Example of Singleton

Example of Prototype

https://www.youtube.com/watch?
v=WgCKVYJRccI&index=8&list=PL9ooVrP1hQOEfi91PCFQMawtBJrPpir7y
Factory Design Pattern

 Factory pattern is used to create and object without exposing object creation
logic to the client and refer newly created object using a common interface.

 Example: In the following example: we are going to create a Shape interface and
three concrete classes( Circle, Rectangle and Square) implementing the Shape
Interface. FactoryClient class gets the desired Shape object from ShapeFactory
on passing information such as (RECTANGLE/SQUARE/CIRCLE).
static factory methods and instance factory methods
Beans are instantiated from Spring container without using new keyword. However, we
can create objects from factories in two different ways via static factory method and
instance factory method

Static factory method

In a factory class, there should be a static method that creates different types of bean
objects. In our example: ShapeFactory is a factory class and retShape() is a static
factory method which creates different types of bean objects such as Circle, Rectangle,
Square etc. In bean configuration file for this factory class, the factory method which
returns bean is specified using factory-method tag and factory class is represented
using class tag. The constructor arguments specified in the bean definition are the
method parameters for the retShape method:

Instance factory method

In this technique, an instance method of a pre-existing bean is used to create another


bean. The factory-bean attribute refers to the bean instance and the factory method
refers to the instance factory method. The class attribute must be left empty.
Bean Life Cycle Management

Springs beans are POJO components that resides within IOC Container and perform
some useful operation. The Spring Framework hides the complex communication that
happens between the Spring Container and Spring Beans. A bean in the factory can
have a very simple or relatively complex lifecycle, with respect to things that happen to
it. Following are the various activities that will take place between the time of bean
instantiation and handover of the bean reference to the client application.

1. The Bean Container finds the definition of the Spring Bean in the Configuration
file.

2. The Bean Container creates an instance of the Bean using Java Reflection API.

3. If any properties are mentioned, then they are also applied. If the property itself is
a Bean, then it is resolved and set.

4. If the Bean class implements the BeanNameAware interface, then the


setBeanName() method will be called by passing the name of the Bean.

5. If the Bean class implements the BeanClassLoaderAware interface, then the


method setBeanClassLoader() method will be called by passing an instance of
the ClassLoader object that loaded this bean.

6. If the Bean class implements the BeanFactoryAware interface, then the method
setBeanFactory() will be called by passing an instance of BeanFactory object.
7. If there are any BeanPostProcessors object associated with the BeanFactory that
loaded the Bean, then the method postProcessBeforeInitialization() will be called
even before the properties for the Bean are set.

8. If the Bean class implements the InitializingBean interface, then the method
afterPropertiesSet() will be called once all the Bean properties defined in the
Configuration file are set.

9. If the Bean definition in the Configuration file contains a 'init-method' attribute,


then the value for the attribute will be resolved to a method name in the Bean
class and that method will be called.

10. The postProcessAfterInitialization() method will be called if there are any Bean
Post Processors attached for the Bean Factory object.

11. If the Bean class implements the DisposableBean interface, then the method
destroy() will be called when the Application no longer needs the bean reference.

12. If the Bean definition in the Configuration file contains a 'destroy-method'


attribute, then the corresponding method definition in the Bean class will be
called.

In Essence, Bean life cycle comprises of following phases:

When we mount an application context and Spring starts up, following a predictable
lifecycle. The actions it performs are:

 Load all bean definitions before constructing beans

 Construct each bean via reflection

 Inject components via setters, autowired methods, etc...

 Post-process the bean

 Make the bean available for use by injection or direct lookup

Alternatively, Life Cycle of bean comprises of:

 Creation of the bean, either by calling a constructor or by a factory method.

 Setting values and bean references to the bean properties.

 Call the setter methods defined in the "aware" interfaces your bean implements.
 The bean is passed to each Bean Post Processor for their
postProcessBeforeInitialization to be executed.

 Calling initialization callback methods.

 The bean is passed again to each Bean Post Processor. Every one of them
executes its postProcessAfterInitialization method.

 The bean is ready.

 When the container is to be destroyed, call the destruction callback methods

Using Post Processors to Handle Customized Beans and Containers

 BeanPostProcessor is interface that tells Spring to do some processing after


initialization some beans.BeanPostProcessor interface, allows the modification of
a bean instance before and after the properties are set. Another extension point
is the BeanFactoryPostProcessor interface which allows direct modification of
bean definitions before a bean is instantiated.

 An ApplicationContext will automatically register and process a bean that


implements either of these interfaces (BeanPostProcessor ,
BeanFactoryPostProcessor ), but a BeanFactory would have to have a
BeanPostProcessor or BeanFactoryPostProcessor registered with it
programatically as given below.

 Since this manual registration step is not convenient, and ApplictionContexts are
functionally supersets of BeanFactories, it is generally recommended that
ApplicationContext variants are used when bean post-processors are needed.

 A BeanPostProcessor gives us a chance to process an instance of a bean


created by the IoC container after it's instantiation and then again after the
initialization life cycle event has occurred on the instance. We could use this to
process fields that were set, perform validation on a bean, or even look up values
from a remote resource to set on the bean as defaults.
 BeanPostProcessor gives us a way to do some operations before creating the spring
bean and immediately after creating the spring bean. This allows us to add some custom
logic before and after spring bean creation. The BeanPostProcessors operate on bean
(or object) instances which means that the Spring IoC container instantiates a bean
instance and then BeanPostProcessor interfaces do their work.

 Notice that the init and destroy methods related to bean are different from bean post
processors. BeanPostProcessors are common for all beans. This example clearly shows
the difference from them.

 To implement bean post processor logic, we need to create a class which implements
BeanPostProcessor interface and two of its methods.

 We can write our own bean post processor to inspect a newly-created bean, and
potentially modify it or return another bean entirely. There are a number of ways to do
this, starting with implementing BeanPostProcessor.

 If we're using a Bean Factory, the only way to register a Bean Post Processor is
programatically through the method addBeanPostProcessor(), while if we're using
Application Context, it is more easier, since all we have to do is to declare the bean
instance in the bean configuration file.

 A bean post-processor is a java class which implements the


org.springframework.beans.factory.config.BeanPostProcessor interface, which consists
of two callback methods (postProcessAfterInitialization(Object bean, String beanName)
& postProcessBeforeInitialization(Object bean, String beanName)). When such a class
is registered as a post-processor with the BeanFactory, for each bean instance that is
created by the BeanFactory, the post-processor will get a callback from the BeanFactory
before any initialization methods (afterPropertiesSet and any declared init method) are
called, and also afterwords.

Example:
BeanPostProcessor interface has two method...

1. postProcessAfterInitialization(Object bean, String beanName) execute after


initialization of each beans in the Spring IoC Container.

2. postProcessBeforeInitialization(Object bean, String beanName) execute before


initialization of each beans in the Spring IoC Container.

MyBeanPostProcessor bean in the Spring IoC Container is automatically called when


before and after any beans (triangle, point) creation. In the below configuration file has
the MyBeanPostProcessor bean without any id attribute.
BeanFactoryPostProcessors
A bean factory post-processor is a java class which implements the
org.springframework.beans.factory.config.BeanFactoryPostProcessor interface. It is
executed manually (in the case of the BeanFactory) or automatically (in the case of the
ApplicationContext) to apply changes of some sort to an entire BeanFactory, after it has
been constructed.

Spring includes a number of pre-existing bean factory post-processors, such as given


below PropertyResourceConfigurer-

and PropertyPlaceHolderConfigurer - implemented as a bean factory post-processor, is


used to externalize some property values from a BeanFactory definition, into another
separate file in Java Properties format. This is useful to allow to developer to declare
some key property as properties file.

Example:
Note:

A bean implementing BeanFactoryPostProcessor is called when all bean definitions will have
been loaded, but no beans will have been instantiated yet. This allows for overriding or adding
properties even to eager-initializing beans. This will let you have access to all the beans that
you have defined in XML

A bean implementing BeanPostProcessor operate on bean (or object) instances which means
that when the Spring IoC container instantiates a bean instance then BeanPostProcessor
interfaces do their work.

The BeanPostProcessors operate on bean (or object) instances which means that the Spring
IoC container instantiates a bean instance and then BeanPostProcessor interfaces do their
work.An ApplicationContext automatically detects any beans that are defined with
implementation of the BeanPostProcessor interface and registers these beans as post-
processors, to be then called appropriately by the container upon bean creation.
BeanFactoryPostProcessor implementations are "called" during startup of the Spring context
after all bean definitions will have been loaded while BeanPostProcessor are "called" when the
Spring IoC container instantiates a bean (i.e. during the startup for all the singleton and on
demand for the proptotypes one)

Summary:

 BeanFactoryPostProcessors – run once after XML is parsed. Can change the


configuration/definition before the beans are instantiated. Property Placeholder
configurator is an example of one.

 BeanPostProcessors – run multiple times (one for each bean) – contain


postProcessBeforeInitialization and postProcessAfterInitialization returning
original bean

Factory Bean Types

There are a number of factory beans which can make container configuration much
simpler. Some of them are:

PropertyPathFactoryBean

Two things are important. First is targetObject ( We assign bean reference) and second
one is propertyPath( We assign some value) . Whatever we assign to propertyPath, it
belongs to property of bean reference assigned to targerObject and client program also
accesses propertyPath value.

Example:
FieldRetrievingFactoryBean

This factory bean retrieves the value of a static or non statc class filed and is most
commonly used to retrieve static constant from a class.

Example:
MethodInvokingFactoryBean

It is a factory bean that returns the result of a method invocation as its output.
Spring Expression Language(SpEL)

Spring Expression Language(SpEL) can be used with XML or annotation based


configuration metadata for defining bean definitions or to wire values into bean's
properties. In both cases, the syntax to define the expressions is of the form
#{ <expression string> }.

SpEL can be used to inject a bean or a bean property(integer, String etc) in another
bean or even to invoke a bean method in another bean. SpEL also supports standard
mathematical,logical, relational, ternary operators(if-then-else) to perform conditional
checking.

Example:
Summary

 We can set literal values of any data type to bean properties using SpEL.

 We can refer other spring beans using SpEL

 Properties of other beans can be referred using SpEL.


 If we need to invoke a static method or reference a constant of a class, the T()
operator is used.

 Ternary Operators( if-then-else) are supported as following:

List of arithmetic and logical operators are:


 The collection selection is represented by “?.[collectionExpression]” operator. We
write the expression within the square brackets.

 Projection allows a collection to drive the evaluation of a sub-expression and the


result is a new collection. The syntax for projection is “![projectionExpression]“.

SpEL based on Annotation

Example:
Resource Location Paths in ApplicationContext
 ClassPathXmlApplicationContext and FileSystemXmlApplicationContext classes
have constructors that take one or more strings pointing to XML file location
which can be used for context definition.

 If the location paths fed to the constructors were not preceded by any prefix such
as http:// or file:; then they will be treated as ClasspathResource and
FileSystemResource by the respective contexts.

 Following definition will treat the path as FileSystemResource

 Following definition will treat the path as UrlResource

 We can also use classpath*: prefix with location string in order to search all
classpath resources matching the name after the prefix.

 We can also use wildcards(e.g. *) with location string.

Declarative usage of Application Contexts

 In order to maintain IoC principle, our application code need not know about the
application context.

 But, if our application code wants to access application context, then it is


accessible through ContextLoader.
Splitting Container Definitions into Multiple Files
We can split up bean factory or application context definitions into multiple files. There
are three different ways for doing this:

 Combining file Fragments Externally

 Combining the File Fragments with the Import Statement

 Combining the File Fragments Programmatically

You might also like