Workshop 1
Workshop 1
Download following applications and packages and follow the instructions accordingly.
<Download Source>:
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-
2133151.html
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.
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 a bean file named Beans.xml
The IOC Container is also called as bean factory. IOC Container is started using the
following code:
Once the bean factory application context has been loaded, desired beans from
BeanFactory is accessed using the following lines of code:
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
- Data Access/Integration
- Web
- Aspect
- Core
- Test
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.
Web layer has components like Web, Servlet, Portlet and Strut Modules. Web
Component will initialize IoC Container using servlet listener.
Aspects: This module helps to integrate another AOP framework like AspectJ.
Spring core layer has components such as core, Beans, Context and Expression
Language
Context: It is used for ApplicationContext( It is also IOC Container). It uses Core and
Beans module.
Java Frameworks
Following are the most commonly used Java Frameworks:
- 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.
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.
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.
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.
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 Configuration
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.
There are many attributes that can be set while defining a bean in a bean
configuration file. Following are few of them:
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.
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).
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:
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.
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
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.
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.
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.
Since in our XML file, we have declared two beans of same type Car i.e. toyota
and suzuki.
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
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:
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.
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.
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.
When we mount an application context and Spring starts up, following a predictable
lifecycle. The actions it performs are:
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.
The bean is passed again to each Bean Post Processor. Every one of them
executes its postProcessAfterInitialization method.
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.
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.
Example:
BeanPostProcessor interface has two method...
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:
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)
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.
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.
We can also use classpath*: prefix with location string in order to search all
classpath resources matching the name after the prefix.
In order to maintain IoC principle, our application code need not know about the
application context.