DURGA SOFTWARE SOLUTIONS
Practical approach to
Spring Framework
Spring Framework 3.x
Mr. Sriman
As part of this we cover Spring Core, AOP, Spring JDBC, Transactions, Spring MVC and
ORM. This includes all the versions of spring starting with 2.0, 2.5, 3.0 and latest 3.1.1
(Spring Annotations as well).Mr, Sriman.
Spring Framework
Contents
1 SPRING FRAMEWORK..
AL Inte oDUCTION TO SPRING FRAMEWORK.
2 SPRING CORE (BASIC)
2.1 STRATEGY PATTERN (DESIGN PRINCIPLE SPRING RECOMMENDS) .
2.1.1 Favor Composition over Inheritance
2.1.2 Always design to interfaces, never code to implementation
21.1 Code should be open for extension and should be closed for modification
2.2 Spring INVERSION OF ConTROL (IOC)...
2.3 TRS OF IOC sssnenene
2.3.1 Dependency Lookup.
2.3.2 Dependency Injection
2.4 CONSTRUCTOR VS SETTER IDECTION .oseseeee
2.5. RESOLVING/MAPPING CONSTRICTOR ARGUMENTS.
2.5.1 Using type attribute
2.5.2 Using index attribute..
2.5.1. Using name attribute..
2.6 CoWECTION INJECTION
2.7. BEAN INHERITANCE
2.8 COLLECTION MERGING
2.9 ThWER Beans
240 UsittG IDREF.
2.11 BEAN ALIASING..
2.12 NULL STRING
2A3 Beat Scores.
2.14 BEAN AUTOWIRING ..
2.15 NESTED BeanFAcroRtes
3. SPRING CORE (ADVANCED) ..
3.1 UsinG P & C ~ NAMESPACE.
3.2 DEPENDENCY CHECK.
3.3. DEPENDS-ON.
3.4 BeaW LFECIOE. _
3.4.1 Declarative approach...
3.4.2 Programmatic approach..
3.5 AWARE INTERFACES..
3.6 STATIC Factory MeTHoD
3.7. INSTANCE.FACTORY METHOD.
3.8 FACTORY BEAN
3.9 MeTHoo REPLACEMENT.
3.10 Lookup MeTHoo Insecrion
3.11 PROPERTY EDITORS...
3.12 INTERWATIONALIZATION (18H) .
100
1.| DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
3.13. BEAN PosT PROCESSOR.
3.14 BEAN FACTORY POST PROCESSOR ....
3.15 EVENT PROCESSING .. es
3.16 BEAN FACTORY VS APPLICATION CONTEXT. vse
4 SPRING ANNOTATION SUPPORT.
4.1 INTRODUCTION To J2EE ANNOTATION.
4.2. SPRING ANNOTATION SUPPORT. a
4.2.1 Working with @Con/iguration and @Bean
4.2.2 Working with @Required.
4.2.3, Working with @Autowire.
4.2.4 Working with @Qualifier sesserserseeie 119,
4.2.5 Working with stereotype annotations @Component, @Repository, @Service and
@Controller, i . 120
4.3 SPRING JAVA CONFIG ANNOTATIONS... sseeneseneee 121
4.3.1. Working with @Inject.
4.3.2 Working with @Named .
4.3.3, Working with @Resource
4.3.4 Working with @PostConstruct and @PreDestro}
5 ASPECT ORIENTED PROGRAMMING (AOP)..
5.1 AOP PrInciptes.
5.2. TYPES OF ADVICES.
5.3. PROGRAMMATIC AOP.
5.3.1 Around Advice.
5.3.2 Before AdVICE ....
5.3.3. After Returning Advice..
5.3.4 Throws Advice...
5.3.5 Pointeut.
5.3.6 Static Pointcut..
5.3.7 Dynamic Pointcut.
5.4 DECLARATIVE AOP.
5.4.1 Around Advice .
5.4.2 Before Advice
5.4.3. After Returning Advice.
5.4.4 Throws Advice
5.5 ASPECT) ANNOTATION AOP
5.5.1 Working with advices ..
6 SPRING JDBC (JAVA DATABASE CONNECTIVITY)..
6.1 CHOOSING AN APPROACH FOR JDBC DATA ACCESS.
6.2. TYPES OF SUPPORTED JDBC OPERATIONS.
6.3. SETTING UP DATASOURCE...
6.4 SAMPLE SCHEMA AND TABLE STRUCTURE.
6.5 USING JDBCTEMPLATE... : .
6.5.1 Working with PreparedStatements using Jdbc Template...
6.5.1 Using JdbcTemplate Operations ..
6.6 _ USING NaMEDPARAMETERIDBCTEMPLATE
151
152
153
2184
154
155
157
165
2 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cel 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
6.7 _ MAPPING SQL OPERATIONS AS SUB CLASSES ...
6.7.1 Using Sqiquery.
6.7.1 Using SqlUpdate
6.8 StmpLeybeclnseRr.
7 SPRING TRANSACTION SUPPORT.
7.1 GLOBAL TRANSACTION
7.1.1 Two-Phase commit.
7.2 LOCAL TRANSACTION ..
7.3. BENEFIT OF SPRING TRANSACTION .
7.4 DECLARATIVE TRANSACTION MANAGEMENT
7.5 TYPICAL Spain PROXECT FLOW...
7.8 ANNOTATION APPROACH TRANSACTION MANAGEMENT.
8 SPRING WEB MVC (MODEL VIEW AND CONTROLLER)
.L_AOVANTAGES OF SPRING WEB MVC...
8.2 DispaToHer SERVLET
8.3 CONFIGURING APPLICATIONCONTEXT
8.4 ConTeouee,
8.4.1 ParameterizableViewController
8.4.2. UnlFilenameViewController
8.4.3 AbstractController
8.4.4 AbstractCommandControlle
8.4.5. SimpleFormController.
8.5 WoRKING WITH VIEWS...
8.6 HANDLER MAPPINGS.
8.6.1. BeanNameUriHandlerMapping.
8.6.1 SimpleUriHandlerMapping
8.7 HANDLER INTERCEPTORS.
8.8 VIEWRESOLvER..
8.8.1 UnlBasedViewResolver..
8.8.1 ResourceBundleViewResolver
8.8.1 XmlViewResolver:
8.9 ABSTRACTCONTROLLER (ANNOTATION).
8.10 ABSTRACTCOMMANDCONTROLLER (ANNOTATION)
8:11 SIMPLEFORMCONTROLLER (ANNOTATION) wos
8.12 REQUESTTOVIEWNAMERESOLVER (ANNOTATION)
9 SPRING ORM (OBJECT RELATIONAL MAPPING)
9.1 INTEGRATING WITH HIBERNATE.
10 SPRING INTEGRATION WITH STRUTS...
3 | DURGA SoFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212343. Phone: 040-64512786Mr. Sriman Spring Framework
pring
Framework
4 | DURGA SOFTWARE SOLUSIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143. Phone: 640-64512786Mr. Sriman Spring Framework
1 Spring Framework
1,1 Introduction to Spring Framework
Spring is a framework, but spring is not a framework similar to struts. Struts
framework supports only developing Web Applications. Unlike Struts, spring
supports various application development types.
In a Web application project we will not have only Web related aspects, apart
from web we will have various other things like managing business logic and
persisting data etc. So, in the above struts only will manages Web aspects and
will not provide anything to manage business or persistency aspects of an
application.
Spring not only manages Web, it can handle other aspects of the application as
well, so it is usually termed as end to end application development framework. So
using spring we can develop not only Web we can develop core java, JEE,
remoting (rmi), distributed, persistency and various other application types.
How many application types spring is supporting. Spring supports all the
application development types in par with JEE. If spring supports all the
application types in par with JEE why should I go to spring, I can use JEE to get
the benefits?
JEE is an API. API stands for Application Programming Interfaces; AP1 contains
interfaces and classes, using which we can build applications. Generally these API
has more number of classes, and these classes are interlinked or inter-related
with each other. For e.g. if I want to execute a sq] query, 1 need statement Object
in jdb¢, but to create a Statement I need to know Connection and to create a
Connection I should know DriverManager. In this way each Class is inter-related
with each other.
So, building an application with few features of JEE also it demands programs to
know all the classes, unless ne end up in learning all he will not be able to start,
developing the applications, So, API's are complex to understand and code.
As API's are huge (contains more number of classes), it takes more time in
learning and learning curve would be high, Apart from this API's will not provide
boiler plate code.
Boiler plate code means this is the piece of code that has to be repeated across
various parts of the application with minimal or no changes. For e.g. I want to
execute a sq} query, to execute a sal query I need to write the following lines of
code,
5 | ourca sortware SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S-R
Nagar, Cell, 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
try
Class.forName("*DriverClassName”);
Connection con = DriverManager.getConnection(url, un, pwd);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery();
If(rs.next()) {
// grab the values
>
}eatch(Salexception sqe) {
// print stack
Executing sql query is a common functionality that everyone has in their projects.
To execute a sql query everyone has to write more or less the same piece of logic.
When it is same, even then also I have to write the same duplicate logic all over
so, itis called boiler plate code.
Instead if we go to spring framework to execute sql query, spring provides one
simple class to do this, we never need to write the whole logic rather we should
just call a method on the spring provided class. Internally spring classes will take
care of doing the above and will provide output.
So, in API's boiler plate code has to be written by programmer, this leads to
writing more and more number of lines of code. This has the following impacts
1, More amount of efforts are required as we need to write more code
2. Developers productivity will go down
3. As more lines of code chances of increasing the bugs will be also high
4. Maintenance cost involved in modifying the code also will be high
In spring as it provides boiler plate logic, we can avoid all the above said
Problems, That is the reason rather than working with JEE we are using spring.
If spring supports all the development types in par with JEE, can Z call spring as @
replacement of JEE? Spring never replaces JEE rather spring complements JEE.
Our application classes are going to talk to spring provided classes and spring
classes internally talks to JEE provided classes. This means without JEE spring
cannot work rather spring enriches and make JEE easier to use for the developer.
This means spring Is complementing JEE to use it easily.
Below diagram depicts the same.
6 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, 5.R.
‘Nagar, Cell, 9246212143. Phoné: 040-64512786Mr. Sriman Spring Framework
=
+
Spring classes
DEE API (classes) {
If spring is providing various applications development types in par with JEE, is
spring is light weight application development framework or heavy weight?
If we look at the spring architecture, it has been designed keeping in view of light
weight, The basic module in the spring is core, it spans across the breath of the
spring, it is the module on which all the rest of the modules are built-on. Apart
from core there are AOP, 3dbc, Transactions and MVC. In this way spring has
several modules and all are dependent and spring core module. Refer to the
below diagram to understand the same.
Spang wes
mvc
ee} | Tae
oe inten Spang ¢ ere
oa ioe
an }
ease.
sel ‘se
s ecm
Here if we observe carefully each and every module don’t have intersection or
cross lines with other, this means there is least or no dependency with other
module, Let’s say if we want to build persistence application, programmer has to
learn/use only spring core and spring Dao (jdbc) to develop application, he don’t
need to use all the other modules to build the same. This shows spring is flexible
enough in offering what you want rather than what is unnecessary. Sa itis called
light weight application framework.
7 | DURGA SOFTWARE SOLUTIONS, 23/3K7, Near Andhya Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman
Spring Framework
Following are the functionalities of each module.
1, Spring Core: - The core module is the heart of spring framework, it spans
horizontally across all the other modules. Core module provides the
essential functionality for spring framework. The primary component of
core module is BeanFactory, an implementation of Factory pattern.
BeanFactory allows you to separate your configuration information and
dependency specification from your actual application code. Using spring
core you can develop a core java application as well.
2. Spring Context: - The spring context module is a configuration file that
allows you to provide the context information to the framework. The spring
context may contain configuration about the pojo's, jndi, email,
internationalization etc.
3. Spring AQP: - AOP stands for aspect oriented programming; it’s a new
programming technic that allows programmers to Induce cross-cutting logic
across several components of your application, Cross-cutting logic implies
any logic or code that has to be applied across several components. For
example transactions, logging, auditing and security are some of the
examples of applications of AGP.
4. Spring DAO: - It is an abstraction of JDBC DAO, In an traditional JDBC
application you have to write lot of boiler plate code like getting the
connection, executing the statements, iterating over the result sets and
managing the resources (e.g.. connection, statement, resultset etc.). Along
with this while working with JDBC code you need to handle lot of annoying
checked exceptions, spring JDBC avoids lot of boiler plate code and it can
manages resources as well as has a meaningful exception hierarchy defined
Jn the framework to handle several types of exceptions that JDBC code
might throw.
5. Spring ORM: - spring framework plugins to several ORM frameworks to
provide its Object Relation tool, the idea behind spring framework is it don’t
want to re-invent the wheel rather wants to make existing tools to be used.
easily in their applications. So, as part of this effort it has provided
{integrations to lot of ORM frameworks like Hibernate, iBatis, JPA etc.
6. Spring Web module:- The web context module is built on top application
context module, providing the context for web-based applications. This
module allows spring to integrate with various other web based frameworks
like jakarta struts etc.
7. Spring Web MVC framework: - This module allows us to build Model-View-
Controller architecture based applications which contains full features for
building Web applications, It varies in many ways from normal web
application frameworks like struts etc. The main advantage of going with
spring web mvc module is view technology is ebstracted from the client and
you can have anything as a presentation tier.
‘Spring framework has been released in early 2004, at that time struts is the
popular fremework in the market and is being highly used. So, struts is peer
competitor for spring, by overcoming lot of hurdles today spring turned to be
8 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nager, Cell, 9246212143, Phone: 040-64512786Mr. Sriman
Spring Framework
the top framework which replaced struts as well. What are the successful
points that made spring framework to be top?
»
2)
Spring is versatile application development framework. Spring can be
integrated into existing projects which may be built-on any technologies to
fill the gap in existing projects/frameworks. Spring is flexible enough to
integrated into any existing technology/framework that is there in the
market to solve the problems that are not addressed by those frameworks.
‘This made spring to be consumed in bits and pieces and eventually turned
to occupy the entire project on spring.
Spring is non-invasive application development framework. Spring will
never force your project to implemeni/extend or use spring classes in your
application code. Spring classes will be separate and our code is separate
still we can leverage spring capabilities in our application. This makes our
classes as pojo classes, which means even we remove spring framework
dependencies still our classes can be compiled under the underlying Jdk
and use the functionality of it.
As we understood spring core is the foundation module on which ali the rest of
the modules are built-on, our journey to spring has to start with spring core.
Considering the importance of spring core module we have divided it into two
parts 1) Spring Core Basic and il) Spring Core Advanced module.
With this separation spring core basic module acts as a foundation, which
enables us to work on other modules (without spring core advanced). Advanced
module covers the powerful features of spring core and is used rarely when the
application demands.
DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143. Phone: 040-64512786Mr, Sriman Spring Framework
2 Spring Core (Basic)
Spring core is the foundation module of the spring framework, as we know to work
‘on any other module in spring we need to know spring core. Why spring core is so
important, what exactly spring core offers to us. Let us try to understand.
In an application we will have multiple classes; all the classes will not play the
same role, Few classes are called Java beans, few are called pojo and some other
are called component or bean classes.
Java bean: If a class only contains attributes with accessor methods (setters &
getters) those are called java beans. These classes generally will not contain any
business logic rather those are used for holding some data in
Pojo: If 2 class can be executed with underlying Jdk, without any other external
third-party libraries support then it is callled Pojo.
‘Component/Bean: If a class has attributes with some member methods. Those
member methods may use the attributes of that class and will fulfill some business
functionality then it is called Component classes.
So a project cannot be built by just one. Say with Java beans we cannot complete
the project rather we need business loaic to perform something, so component
classes will also exist in a project.
So, in a project do we have one component class or multiple component classes.
By just having one we cannot complete rather we will have multiple component
asses. Every component class in our project will talk to other or will not? Every
component class cannot be isolated; it has to talk to some other component classes
in the project to fulfill the functionality.
For e.g.
dass A {
public void m0) {
+
,
dass 8 {
public int m2() {
az
3
In the above code we have class A and class B. class A m1() method may have to
talk to m2() method of the class 8 to fulfill business functionality, so these two
lasses are called dependent on each other as, unless B is there A cannot be used.
So how to make the B available to A or how to manage the dependencies between
‘and B is what spring core is all about.
10 | DURGA SOFTWARE SOLUTIONS, 23/387, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
Now the question here is can I give any two classes and ask it to manage or spring
cannot manage any arbitrary classes. Spring can manage any two arbitrary classes
but in-order it to be effective spring recommends us to design our classes following
some design guidelines, so that those components will be loosely-coupled. The
spring can effective manage them.
Spring recommends us to design our classes following a design pattern called
Strategy design pattern, Strategy design pattern is not belonging to spring, it is the
pattern that comes from “Gang of four design patterns”. If we design our classes
following strategy design patterns the spring can manage them easily.
So, let’s first examine the design principles and then we focus on Spring Core IOC.
2.1 Strategy pattern (Design principle spring recommends)
Strategy pattern lets you bulld software as loosely coupled collection of
interchangeable parts, in contrast with tightly coupled system. This loosely
coupling makes your software much more flexible, extensible, maintainable and
reusable.
Strategy pattern recommends mainly three principles every application should
follow to get the above benefits those are as follows
+ Favor Composition over Inheritance
+ Always design to Interfaces never code to Implementation
+ Code should be open for extension and closed for modification
Let us examine all the three principles by taking an example
2.1.1 Favor Composition over Inheritance
Every class in order to perform a task has to talk with other class to get the
things done. A class can use the functionality of other class in two ways,
1) Through Inheritance - Inheritance is the process of extending one class from
another class to get its functionalities.
2) Composition ~ A class will hold reference of other classes as attributes inside
it,
Using Inheritance you always express relation between two classes as IS-A
relationship. Composition always expresses relation between two classes as HAS
A relationship.
When should I go for Inheritance and when should I go for composition?
The problem with most of the programmers is they will always choose the option
of inheritance to use the functionality of other classes. But this may not be apt in
all cases;
‘U1 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R
Nagar, Cell, 9246232343. Phione: 040-64512766Mr. Sriman Spring Framework
We have te go for inheritance only when all the behaviors (methods) of your base
class can be commonly sharable across all the derived classes.
In case if my class wants to use only few behaviors of the other class, rather
extending my class from the other I should go for composition,
If we look composition has more number of advantages when compared with
inheritance as described below.
> Most of the use-cases are solvable through composition rather than
inheritance. If we look no class wants to use all the services of other class,
rather it wants to use only few method of other class. Just for the sake of
using few methods of other class we should not go for inheritance rather
than composition is recommended
> Acclass most of the time wants to use behavior of more than one classes,
so to use the functionality of other class if we choose inheritance here we
have to extend our class from more than one class. But most of the
programming languages will not support extending a class from more than
one class (multiple inheritance). Only alternate here is to use composition.
> When we go for inheritance our classes will become fragile. Fragile means
those will become delicate or easily breakable. To understand this let's
consider one example. I have a class A as shown below.
dass A {
int mi) {
11 some logic
return 10;
-
>
Ihave one more class B which extends from A and overriding method m1()
as shown below.
class B extends A{
@Override
int maQ) €
1/ some logic
int i = super.m1();
J{ calculate
return i;
d
ug
Now class A has been written by some other developer and class B has.
been written by other developer. After sometime author of the class A has
felt the return type of the method needs to be changed and has modified
from int to float as shown below.
12 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show roam, S.R
Nagar, Cell. 9245212143, Phone: 040-64512786Mr. Sriman Spring Framework
class A {
float mi() {
1/ some logic
return 10.24;
,
3
Now author of the class A has changed the return type from int to float,
immediately class B will not compile, why? When we are overriding the
super class method and sub-class method signatures should be same. But
in the super class for the method m1() return type is float and in sub-class
the return type is int, so it is not an valid overriding.
Even it is not valid overloading, because parameters of my super class
method m1() and parameters of my sub-class methods are same. It means
we have two methods with same name in the class which is not allowed. So
it results in compilation error.
Here the change in the super class will not just break the sub-class even
the classes using the sub-class also will gets affected and all the
componenits using your sub-class need to undergo changes. It results in
high maintenance cost and chances of increasing the bugs will also be
more.
If we go for composition in the above case which means class 8 is not
extending from class A rather it is using the reference of A inside B to call
its methods.
class B {
private Aa;
int m1) {
// some logic
int i= ami;
// calculate
return
>
}
Now ifthe return type of m() in class A changed I just need ta type cast
the value in the 6 to int rather than modifying the return value as shown
below.
13 ] DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
‘Nagar, Cell, 9246212143, Phone: 040°64512786Mr. Sriman Spring Framework
class B {
private A a;
int m1() {
// some logic
int i =(float) a.m1();
// calculate
return i;
>
+
So, any changes to the class A can be handled in B and those changes will
not affect the classes using B. Here 8 can suppress all those changes at its
level, so that those do not propagate to other classes.
> Testability of the code will be easy when we go for composition instead of
using inheritance,
For e.g. I have a class Engine and it has a method start(). I have another
class Bus it has a method called drive()..
If my Bus wants to use the Engine class I have two options one is
inheritance and other one is composition. But inheritance makes my code
difficult to test let’s try how?
Inheritance ‘Composition
Engine Ename Bue
ripe che
[ran boat n= boa) fraived
‘Bus
[raven
For example in the above case my Engine is not fully implemented, only the
methods are declared, still the logic has to be written. But meanwhile the
other developer as he knows the methods of the Engine he has written the
logic for Bus.
Now to test class Bus I need the Engine, so to facilitate the testing I need
to create dummy class for Engine, using which I can test my drive method
of the Bus as shown below.
14 | DURGA SOFTWARE SOLUTIONS, 237/387, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman
Spring Framework
1 dummy class or prototype class for
class PrototypeEnginel {
public boolean start() {
// do something.
return true;
+
}
the actual engine
Now I need to modify the Bus class to
test it as shown below.
extend it from PrototypeEngine1 to
class Bus extends PrototypeEnginel {
public void drive() {
boolean isStarted = false;
isStarted = super.start(),
if(isStarted == true) {
// do something
} else {
// do something
ae
+
x
But just testing against one Dummy or Prototype class I cannot certify my
Bus is working, rather I should be able to test it against lot of prototype
‘engines in this way. So always I need
which I need to extend from.
to keep on changing the class from
class Bus extends
PrototypeEngine2 {
public void drive() {
boolean isStarted = false;
isStarted = super.start();
ifisStarted == true) {
/1.do something
} else {
// do something
-
}
}
class Bus extends
PrototypeEngine3{
public void drive() ¢
boolean isStarted = false;
isStarted = super.start();
iffisStarted == true) {
1/ do something
} else {
1/ do something
}
,
J
45
If you look as Inheritance makes a class static reference to another class it
makes harder to test my Bus class against different prototypes of Engine
and demands code changes to test against different. Instead if I use
composition it gives me lot of flexibility as shown below.
DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebck Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512785Mr. Sriman Spring Framework
Create multiple prototype Engine classes extending from the abstract class
Engine as shown below,
[Pratorpstnpu?|
[an boa
Now create Bus class which has reference of Engine inside it (composition).
———
class Bus {
private Engine engin
public Bus(Engine engine) {
this-engine = engine;
public void drive() {
boolean isStarted = false;
isStarted = engine.start();
if(isStarted == true) {
// do something
} else {
// do something.
Now in my test class while testing the Bus pass different prototype Engines
as input which makes your object to point to different Engines without
modifying the code as shown below.
class TestBus {
Public void testDrive() {
new Bus(new PrototypeEngine1()).drive();
new Bus(new PrototypeEngine2()).drive();
+
z
Now I can test Bus without modifying the code by making it point to several
references of EnginePrototype which makes my code easily test.
16 | ouRGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show roam, $.R
Nagar, Cell. 9246212143. Phone: 040-€4512786Mr. Sriman Spring Framework
So let’s try to understand how to use inheritance by taking an example,
Gr Fg,
paekety pariverd
Hhonk() FY)
Ayt) boot)
h
2830 ot vali ese 1 dive ot val tor Fgh
In the above diagram I have a vehicle which contain drive (), fly (). and blow horn.
(honk ()). So I want to represent a Car and a Flight which is of Vehicle type. If I
try to express this with Inheritance I will end up in implementing fly method in
Car class as empty and drive method in flight class as empty (because the fly and
drive are in-appropriate for Car and Flight respectively).
So to overcome this modifies your class structure into two hierarchies as Drivable
and Flyable making Vehicle as sub-classes shown below.
was ri
“s mo
(er ge
{
Ese oa
But the problem with above approach is your design model is rigid (closed).
‘Through the above design you are stating you can have a vehicle which can either
fly or drive, But in future if I have a vehicle which can drive as well as fly then itis
ot possible to represent that kind of vehicle with the above design. This may
leads to re-designing the entire application,
17 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S-R
Nagar, Cell, 9246212143. Phone: 040-64512786Mr, Sriman Spring Framework
So, by the above example it is dear that we can't represent all the problems
through inheritance. In order to solve this, Composition would be more apt than
Inheritance. Below diagram shows the solution for the above described problem.
While
1 [aeivabie 7 orivante
[eiyabie : rlyable
Pronk) ji
+ | ea setOrivable(in drivable : orivable) + | era
[setriyable(in fayble : Flyable)
Drivabie Fiyabie
[rivet vO,
or Fite
barat) Ayo.
Inonk¢) Ihonk()
In the above diagram Vehicle is an abstract class. We created two more concrete
classes Drivable and Flyable which contains logic for drive () and fly ()
respectively. As every vehicle may contain drive() or fly() or both, we declared
both these classes as attributes inside Vehicle class.
Now class Car & Flight extends from vehicle. Let’s say in the class Car we have
the method drive() it will calls the drive() method on the super class attribute
drivable as shown below.
‘lass Car extends Vehicle { class Flight extends Vehicle ¢
public Car() { | public Flight() {
setDrivable(new Drivable()); setFlyable(new Flyable());
+ +
public void drive() { Public void fly() {
drivable.drive(); flyable.fly();
Dh
7 ce
In the same way Flight is another class extends from Vehicle and it only sets the
flyable object reference and calls the fly() method to use the functionality.
‘Tomorrow if we have a vehicle which can drive() and can fly() then in my class we
need to set the references of both Drivable and Flyable and can use it.
Using composition now we have a flexibility of having both fly() and drive() as
part of our sub-classes, this cannot be achieved by inheritance.
18 | DURGA SOFTWARE SOLUTIONS, 23/3KT, Near Andhra Bank Opp: Reebok Show room, S.R.
Nagar, Cell. 9246212143, Phone: 04064512786Mr. Sriman Spring Framework
.2 Always design to interfaces, never code to implementation
In our earlier discussion we understood most of the times we should prefer to use
Composition rather than inheritance. Yes, but when we use composition, the
coupling between the classes will be high.
For e.g When Vehicle Is referring to Drivable or Fyable it means without the
presence of Drivable and Flyable class Vehicle cannot be complete. Let’s say we
have a new car came which uses an Automatic Drive technic rather than normal
‘one or a new Flight which needs to by fly with new technic. It cannot be changed
as Vehicle holds the concrete references of Drivable and Flyable classes we cannot
change it.
Now let's declare two interfaces IDrivable contains drive() and IFlyable contains
fiy() method. Declare these two interfaces as attributes in Vehicle class. Now
create DefaultDrivable and DefaultFlyable as implementations of those interfaces.
As Vechicle holds the interface reference type we can set those to object of its
implementation to those references. In future we need new drive() technic, we
can create one more implementation of IDrivable interface and can plug-in. Here
is the below diagram depicting the same.
wre
nonk()
Sela cat a2(aF ar tatte © WW-aveste)
HeijatioQr “Les ¢ TFyabIs)
leray()
Snare
TDeivabi baeved)
efactibeiante [ cara
|
ica Cor Faght i)
Farivey av,
Ioak() Ienonk()
2.1.1 Code should be open for extension and should be closed for modification
Let’s say a new car came, and it uses a different drive technic, now we don’t
need to modify the DefaultDrivable class rather we can create one more
implementation of the IDrivable interface and can set it as a reference to drivable
reference. If we modify the existing code the chances of increasing the bugs
would be more, rather than our design should be flexible enough to plug-in new
implementations when required, our earlier design depicts the same.
19 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
2.2 Spring Inversion of Control (IOC)
Let's try to understand the IOC by taking one example, first let us design our classes
by following strategy design pattern, and then we will identify the pit-falls in it and will
understand how to simplify it using IOC
We have a MessageWriter class which will write the message to the console. The
MessageWriter class will get the message from MessageProducer class. But we have
multiple types of MessageProducers like TextMessageProducer, HTMLMessageProducer
ete.
So the MessageWriter will talks to the message producers through an interface
IMessageProducer, which defines a method formatMessage. This has been explained in
the below diagram.
(——ressageiriter 7
i taherzage(in message + String)
4
Winterfacer
DiassageProducer
fornatTessage( im passage + string) 7 String
zs
TenthessagePromeene Tierrauehroducer
Seema ee Nee eee eee
Fofaatresrege tn mesroee 7 Sera) Sing | © Foraathestoge in nestage Seg) See]
Hf you observe carefully the above design has followed all the design principles that
spring recommends. Code fragment for the above classes are as shown below.
IMessageProducer.java
package com.ioc.beans;
public interface IMessageProducer {
String formatMessage(String message);
Ee
20 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, §.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr, Sriman
TextMessageProducer.java
Spring Framework
HTMLMessageProducer.java
package com.ioc.beans;
public class TextMessageProducer
implements IMessageProducer {
public String formatMessage(String
package com.ioc.beans;
public class HTMLMessageProducer
implements IMessageProducer {
public String formatMessage(String
message) { message) {
return “Hello” + message + "!"; return
} " ” +
} message + " ";
y
A eee
MessageWriter,java
package com.ioc.beans;
public class MessageWriter {
private IMessageProducer messageProducer;
public void writeMessage(String message) {
// instantiate messageProducer with concrete implementation class
messageProducer = new HTMLMessageProducer();
String formattedData = messageProducer.formnatMessage(message);
‘System.out.printin(formattedData);
}
d
MessageTest.java
package com.ioc.beans;
public class MessageTest {
Public static void main(String args[]) {
MessageWriter writer = new MessageWriter();
writer.writeMessage("Welcome to Spring”);
y
ti
Even you followed the recommended design principles, it has two problems.
* In your MessageWriter class inside the writeMessage method you have hardcoded
the concrete class name HTMLMessageProducer while instantiating
messageProducer attribute. If you want to switch between HTMLMessageProducer
to TextMessageProducer you need to modify the source code of the MessageWriter.
21 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R.
Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
+ MessageWriter to use the services of HTMLMessageProducer it is trying to create
the object of it.If MessageWriter is trying to create the Object of
HTMLMessageProducer or TextMessageProducer, it has to know the complete
instantiation process of creating those. Some classes can be created out of calling
new Operator, but some classes should be created using complex instantiation
technic like sometimes let’s say ‘A’ want 'B’ it has to create 'B’ but to create 'B’ itis
using ‘C’ so first create ‘C’ and then ‘B’ finally ‘A’ can use it.
‘This tells unless ‘A’ instantiates all the dependents that ‘B’ needs it cannot use, and the
same piece of code has to be written by all the other classes which ever want to use
°B’. So, code is duplicated across the logic to create 'B
To avoid the above problems instead of MessageWriter creating the Object of
IMessageProducer implementation class, it should externalize this functionality to
someone else, that’s where factory classes come into picture.
In Jdbc Connection is an interface & Database vendors will have the implementation, if
‘want to switch between Oracle DB to MySql Database, I don't need to modify the
code because my classes are talking to the interfaces, there are not talking te create
implementations.
But in-order to create Connection I can’t create the Connection as
Connection con = new Connection();
Because Connection is an interface, to instantiate it we need implementation of it. We
don’t know what is the implementation of Connection to instantiate? That’s where
DriverManager (factory) will find the implementation class and instantiate it.
So, here DriverManager acts as a factory for creating the object of Connection
interface. Factories are the classes who will manufacture the objects of other classes.
They hide the complexity in creating the objects of other classes.
Let's say 1 want @ Car, but ta drive a Car I don’t need to know how to create a Car
rather I just need to go to a Car factory, factory will create a car and gives te us.
Similarly if we want IMessageProducer Implementation, we can create
MessageProducerFactory which will have a factory method, it creates the Object of one
of the implementation of IMessageProducer and returns to use as shown below.
22 | DURGA SOFTWARE SOLUTIONS, 23/38T, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
public class MessageProducerFactory {
Public static IMessageProducer createMessageProducer(String type) {
if(type.equals(*html”)) {
return new HTMLMessageProducer();
Jelse ifltype.equals("text”)){
return new TextMessageProducer();
+
return null;
ie
+
In the above class I have a factory method called createMessageProducer upon calling
will create the one of the implementation of IMessageProducer and returns to us based
on the “type! we passed as input.
With the above we are able to avoid the two problems we discussed earlier, now we
don’t need to refer to the concreate class name of other class and we don’t need to
know the complex instantiation process of creating the object of other classes. The
modified code for MessageWriter shown below,
Modified#1 - MessageWriter,java
package com.ioc.beans;
public class MessageWriter {
private IMessageProducer messageProducer;
public void writeMessage(String message) {
messageProducer = MessageProducerFactory.createMessageProducer(“htri”);
String formattedData = messageProducer.formatMessage(message);
System.out. printin(formattedData);
>
+
$f we look at the above code, even we are able to avoid the concreate class name of
other class still we are referring to the logical name of other class as ‘html’ or ‘text’
again there is a level of coupling.
By this we understood when we create the object of other class or when we try to get
(pull) the object of other class through some factory, our classes will be tightly coupled
to other classes. To avoid this, my class should not have the code for creating or
pulling rather the dependent object need to be injected.
To inject we need to create a setter or constructor araund the dependent attribute of
our class. So, whoever wants to use MessageWriter will set the dependent and call the
method?
Below is the modified version of MessageWriter far the same. Here test class is setting
IMessageProducer implementation and calling the method writeMessage()
23 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R.
‘Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
Modified#2 - MessageWri
package com.ioc. beans;
public class MessageWriter {
private IMessageProducer messageProducer;
Public void writeMessage(String message) {
String formattedData = messageProducer.formatMessage(message);
System.out.printin{formattedData);
3
public void setMessageProducer(IMessageProducer messageProducer)<
this.messageProducer = messageProducer;
=
3
Modified#1 - MessageTest.java
package com.ioc.beans;
Public class MessageTest {
public static void main(String args{]) {
MessageWriter writer = new MessageWriter();
IMessageProducer messageProducer = new HTMLMessageProducer();
writer.setMessageProducer(messageProducer);
writer writeMessage("Welcome to Spring”);
}
+
If you see the MessageWriter class it is loosely coupled from HTMLMessageProducer
and now it can talk to any IMessageProducer implementation classes. Second thing
MessageWriter doesn’t need to bother about how to instantiate IMessageProducer
implementation class, because IMessageProducer implementation class will be injected
by calling setter method on it,
Even though we made our business class loosely coupled from specific implementation,
but still we hardcoded the HTMLMessageProducer in MessageTest class. If you want to
use TextMessageProducer instead of HTMLMessageProducer your main method should
be modified to instantiate TextMessageProducer class and should pass it to the
MessageWriter via calling its setter.
So, at some place in your code you are hard coding the concrete class references, in
order to avoid this you need to use the Spring IOC.
24 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R.
Nagar, Cell. 9246212143. Phone: 040-64512785Mr, Sriman
Spring Framework
2.2 Types of IOC
IOC is a principle, 10¢ means collaborating objects and managing the lifecycle of it.
There are two ways using which we can collaborate objects
10C is of two types; again each type is classified into two more types as follows.
1)
2)
2.3.1
»
Dependency Lookup
‘a. Dependency Pull
b. Contextual Dependency lookup
Dependency Injection
a. Setter Injection
‘b. Constructor Injection
Dependency Lookup
Dependency lookup is a very old technic which is something exists already and
most of the J2EE applications use. In this technic if a class needs ancther
dependent object; it will write the code for getting the dependency, Again this
has two variants as said above.
Dependency Pull
Miwe take a J2EE Web application as example, we retrieve and store data from.
database for displaying the web pages. So, to display data your code requires
connection object as dependent, generally the-connection object will be retrieved
from a Connection Pool. Connection Pools are created and managed on an
Application Server. Below figure shows the same.
es ‘Component
Your component will look up for the connection from the pool by performing @
INDI lookup. Which means you are writing the code for getting the cone
indirectly you are pulling the connection from the pool, So, it is called
dependency pull.
Pseudo code
Context ctx = new InitialContext();
DataSource ds = ctx.lookup("jndi name of cp”);
Connection con = ds.getConnection()
|} pulling the connection
25 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near anthra Bank Opp: Reebok Show room, S.R.
Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
2) Contextual Dependency Lookup
In this technic your component and your environment/server will agree upon a
contract/context, through which the dependent object will be injected into your
code,
For e.g If you see a Servlet API, if your servlet has to access environment
specific information (init params or to get context) it needs ServietConfig object.
But the ServletContainer will create the ServietConfig object. So in order access
ServletConfig object in your servlet, you servlet has to implement Servlet
interface and override init(ServletConfig) as parameter. Refer the below figure.
Senet Cong willbe injected into Servet
bye Container
arvet
[Dn Soong
[iii cn: Serer
Then the container will pushes the config object by calling the init method of the
servlet. Until your code implements from servlet interface, container will not
Pushes the config object, this indicates servlet interface acts as a contract
between you and your servlet so, and it is called Context Dependency Lookup
(DL).
2.3.2 Dependency Injection
Even though spring supports the above mentioned two technics, the new way of
acquiring the dependent objects is using setter injection or constructor injection.
This is detailed as below.
1) Setter Injection
In setter injection if an object depends on another object then the dependent
object will be injected into the target class through the setter method that.
has been exposed on the target classes as shown below.
26 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell, 9246212143. Phone: 040-64512786Mr. Sriman
Spring Framework
In the above diagram MessageWriter is the target class onto which the
dependent object IMessageProducer implementation will be injected by
calling the exposed setter method.
2) Constructor injection
In this technic instead of exposing a setter, your target class will expose a
constructor, which will take the parameter of your dependent object. As your
dependent object gets injected by calling the target class constructor, hence
it is called constructor injection as shown below.
Let’s modify the earlier example to inject the IMessageProducer into MessageWriter
through setter injection and constructor injection.
If we want our class objects to be managed by spring then we should declare our
classes as spring beans, any object that is managed by spring is called spring Bean.
Here the term manages refers to Object creation and Dependency injection (via setter,
constructor etc...).
So in our example we want MessageWriter and IMessageProducer implementation
Classes to be created and injected by spring, so we need to deciare them spring in a
configuration file called “Spring Beans configuration”.
27 | ovRGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512785Mr. Sriman Spring Framework
“Spring Bean configuration" is an xml file in which we declare all the classes as beans,
so that those will be managed by spring. We need to use
tag to declare a class
as spring bean. The below fragment shows how to create a class as spring bean.
Spring Beans Configuration (application-context.xml)
The org.soringframework.beans and org.springframework.context packages are the
basis for the Spring Framework’s IOC Container. By just declaring our classes as beans
in the spring bean configuration files automatically objects will not be created, rather
we need to give this configuration as input to BeanFactory. The BeanFactory is an
interface and the implementations of it know reading the configuration file and
Instantiating the beans.
We can declare the information about our classes in multiple ways for e.g. in properties
file or xml or annotations. Based on the style of configuration we need to use one of
the implementations of BeanFactory interface. Here We are using xml for configuring
our class information, so we should use XMLBeanFactory implementation.
Creating IOC Container
BeanFactory factory = new XmiBeanFactory(new ClassPathResource(
“com/injection/common/application-context.xml"));
Now to get the bean from the spring, we need to call the method
factory.getBean("beanId”). Here beanld refers to the id with which we configured it in
spring bean configuration.
Below is the code fragment explaining how to use the beans or objects created by
spring.
28 | DURGA SOFTWARE SOLUTIONS, 23/3KT, Near Andhra Bank Opp: Reebok Show room, 5.
Nagar, Cell, 9246212143. Phone: 040-64512786Mr, Sriman Spring Framework
package com.injection.test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans factory xml.XmiBeanFactory
import org.springframework.core.io,ClassPathResource;
import com.ioc,beans.MessageWriter;
public class MessageWriterTest (
public static void main(String] args) {
BeanFactory factory = new XmiBeanFactory(new ClassPathResource(
“com/ioc/common/application-context.xml"));
MessageWriter messageWriter = factory.getBean("messageWriter",
MessageWriter.class);
// now get message producer and set it to message writer
IMessageProducer messageProducer =
factory. getBean("htmiMessageProducer”, [MessageProducer.class);
‘messageWriter.setMessageProducer(messageProducer);
messageWriter.writeMessage("Welcome to Spring");
In the above example we are not creating the beans rather spring itself has created the
objects for our classes we are just getting those objects from Spring. After getting
MessageWriter and HTMLMessageProducer, we are explicitly calling the
setMessageProducer(..) method to inject messageProducer into MessageWriter class,
because in our declaration (spring bean configuration file) we just asked spring to
create the objects of our classes, we never asked him to manage the dependencies.
As both the objects created by spring, we got them and calling setter to inject one into
another, so if I don’t want to use HTMLMessageProducer instead I want to use
TextMessageProducer, again I need to modify the code why? Because we are managing
the depencdencies. So I should not create or should not pull rather pass the object of
dependent HTMLMessageProducer to Target MessageWriter using spring.
Will spring does? Yes, as both the objects are created by spring, we can request spring
to help us in calling a setter method or constructior other guy by passing
HTMLMessageProducer or TextMessageProducer. How? Only way of talking to spring is
through spring bean configuration file.
Instead of us injecting we want spring to create these objects and inject one into
another, in order to do this we need to deciare all the classes in configuration file
including their dependency relations.
29 | OURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show fom, S.R
Nagar, Cell. 9246212143. Phone: 040-64512785Mr. Sriman, Spring Framework
Spring Beans configuration File (application-context.xml)
"http://www. springframework.org/schema/beans”
'http://www.w3.0rg/2001/XML Schema-instance”
xsi:schemaLocation="http.//www.springframework.org/schema/beans
http://www. springframework.org/schema/beans/spring-beans.xsd">
tag the core container will detects
and throws BeanCreationException.
If dasses have cyclic dependencies
via constructor, these dependent
beans cannot be configured through
Constructor Injection.
The dependent objects are not
injected while creating the target
classes object. Those will be
injected after the target class has
been instantiated, by calling the
setter on the target object.
In case of setter injection your
dependent objects are optional to
be injected. Even you don’t provide
the tag while declaring
the bean; the container will creates
the Bean and initializes all the
properties to their default.
Cyclic dependencies are allowed in
Setter Injection,
33
DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R.
‘Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
2.5 Resolving/Mapping Constructor Arguments
Even we pass the required amount of parameters in calling a constructor spring will not
be able to determine the correct constructor for the arguments we passed and result in
an error or in-correct mapping. This means spring will be confused sometimes in calling
a constructor.
We can solve this confusion in three ways:
a) Using type attribute
b) Using index attribute
c) Using name attribute
Let's consider a case where spring cannot resolve the constructor arguments directly.
2.5.1 Using type attribute
Robot.java
package com.cc.beans;
lpublic class Robot {
private int id;
private String name;
private String type;
Public Robot(String name, String type) {
this.type
this.name
+
public Robot(int id, String type) {
this.id = id;
this.type = type;
>
@Override
Public String toString() {
Feturn "Robot [i
+id +", name="+ name +", type=" + type + "]";
3
in the above example the Robot class has two constructors one will take (String,
Sting) and another takes (int, String) as parameter, if you configure this class as
spring bean, you need to pass the argument one of these.constructors. Let's say we
are passing the values to the constructor as below
34 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.8
Nagar, Cell. 92465212143, Phone: 040-64512786Mr. Sriman.
api
Spring Framework
ation-context.xml
/
="1.0" encoding="UTF-8"2>
“http://www. springframework.cra/schema/beans"
xmins:xsi="http://Wwww.w3,0rg/2001/XMLSchema-instance”
xsi:schemaLocation="nttp://www.springframework.org/schema/beans|
Guess with the above bean definition which constructor will be called on our class? It
will call (St
19, String) argument constructor, because by default any value that you
configured in the spring bean configuration file will be treated as String, se even you
pass 10” integer value spring will confuse and treats it as String rather than integer
and invokes the two String argument constructor. To resolve this we need to use type
attribute at the bear tag level as shown below.
Modified #1 - application-context.xml
I
I
/www.springframework.org/schema/beans”
‘www.w3.0rg/2001/XMLSchema-instance*
http://www.springframework.org/schema/beans|
In the above configuration we are telling the value we are passing is of type “integer”
and we are asking the spring to map it to an appropriate constructor as per it.
35 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman. Spring Framework
2.5.2 Using index attribute
Let us consider one more scenario where the same robot class contains one constructor
t, String) as shown below.
Modified - #2 Robotjava
[package com.cc.beans;
lpublic class Robot {
private int id;
private String name;
private String type;
public Robot(int id, String name) {
thi H
@Override
public String toString() {
return "Robot [id=" + id +", name
>
+ name +", type=" + type + "J";
If you try to configure this as spring bean, you need to configure the values in the
‘same order of argument declaration. In case if the order mis-match then it will not be
‘able to detect the relevant constructor. To resolve this you need to use index. Index
lets you point the argument declaration to method parameters irrespective of the order
in which those has been declared in configuration as shown below.
Modified - #2 application-context.xml
"1.0" encoding="UTF-8"?>
i eae
When we use index, if there are n parameters for the constructor we need to specify
the index value for n-1 parameters only.
36 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell, 9246212143. Phone: 040-64512786Mr, Sriman Spring Framework
2.5.1 Using name attribute
Instead of using index, the other way of mapping the parameters to the arguments of
the constructor is using name attribute at the bean tag level, show as below.
package com.cc.beans;
import java.beans.ConstructorProperties;
public class Robot {
private int id;
private String name;
private String type;
@ConstructorProperties({ "id", "name" })
public Robot(int id, String name) {
this.id
this.name = name;
x
@override
public String toString) {
return "Robot [
+ name +", type=" + type + "J"
3
To use a name attribute at spring bean level to map the parameters, either we need to
‘compile the code with -debug flag or we need to annotate our constructor with
@ConstructorProperties as shown above.
"1.0" encoding="
‘http: //www.springframework.org/schema/beans"
'nttp://www..w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http: //veww.springframework.org/schema/beans|
http://www.springframework.org/schema/beans/spring-beans.xsd">
Run the above program you should see the output as expected.
37 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phane: 040-64512786Mr. Sriman Spring Framework
2.6 Collection Injection
‘Spring not only supports inject primitives and objects to be injected as dependents into
target classes, along with that spring even supports injected collections as dependent
objects into the target class.
In spring you can inject four types of collections as dependent objects into your target
classes. Those are List, Set, Map and Properties. Spring has provided convenient tags
that allow you to create these objects in declarations and allow you to inject into your
target classes,
1) Injecting List
Course.java
[package com.cdi.beans;
limport java.util.List;
limport java.util. Properties;
limport java.util.Set;
public class Course {
private List subjects;
Public void setSubjects(List subjects) {
this.subjects = subjects;
>
17 toString();
In the above Course class we have List of subjects, while configuring the course
class as a spring bean, we want to inject subjects list as well. In order to inject the
list we need to use a tag or tag. Either using or
has the same behavior, “util” namespace has been introduced from spring 2.0. The
idea behind having the “util” namespace separately is to have namespace
‘compartmentalization.
Below code snippet shows the configuration for injecting list.
38 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.A
Nagar, Cell, 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
application-context.xml
C
C++
Jeva
‘
I
i 2) Injecting Set
‘As you know the difference between list and set, list allows duplicates whereas set
doesn't allow duplicates, You can inject set as dependent object using the tag
. Set has set of values, so the tag Contains as child element,
the same has been demonstrated in the below code.
\ Course.java
i package com.cdi-beans;
i import java.util.Set;
i public class Course {
i private Set faculties;
public Course(Set faculties) {
this.faculties = faculties;
+
public void showFaculties() {
‘System.out.printin(*Faculties :");
for (String f : faculties) {
i System.out.printin(f);
application-context.xml
Mark
John
<
‘com.cdi.beans.Course">|
i 39 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
i Nagar, Cell 9246212143. Phone: O80-04512786Mr, Sriman. Spring Framework
3) Injecting Map
Map Is a collection which contains key and value pair. In case of Map the key can be
any type and value can be any type. In order to create a map and inject into target
dlass you need to use
40 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell, 9245212143. Phone: 040-64512786Mr. Sriman Spring Framework
4) Injecting Properties
Properties is also a Key and Value type collection, but the main difference between
Map and Properties is Map can contain key and value as object type, but the
Properties has key and value as string only.
In order to inject properties as dependent object, you need to use the tag ,
this has sub elements value nere.
Refer to the following example for the same.
Course.java
package com.cdi.beans;
import java-util.Properties;
public class Course {
private Properties facultySubjects;
public void setFacultySubjects(Properties facultySubjects) {
this.facultySubjects = facultySubjects;
y
Public void showFacultySubjects() {
‘System.out.printin("Faculty --> Subjects");
for(Object 0 : facultySubjects.keySet()) {
System.out.print(o +" --> ");
System.out.printin(facultySubjects.get(o));
>
y
+ fiesannsaaaieesaaaaaaceeaaal
application-context.xml
‘C
S.E
41 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp:
Nagar, Cell. 9246212143. Phoné: 040-64512786Mr. Sriman Spring Framework
2.7 Bean Inheritance
Inheritance is the concept of reusing the existing functionality. In case of java you can
inherit a class from an Interface or another class. When you inherit a class from
another class, your child or derived class can use all of the functionalities of your base
class.
A bean in spring is a class configured with some configuration around it wsing which
spring creates the object for it. Bean inheritance is the concept of re-using the
configuration property values of one bean inside another bean is called bean
inheritance.
T have a class and I configured it as a bean with some values that has to be injected
while creating. For the same class I want 10 beans of such type, so how many times I
need to configure it as bean, with the same configuration changing the bean id I need
to configure 10 beans.
This makes your configuration bulgier (more) and any change for one of the value of
the property need to be changed across all the 10 beans, duplication of configuration
results in more maintenance cost.
Is there any alternate to copy the values of one bean into another bean rather than re-
declaring the entire configuration? That’s where bean inheritance comes into picture.
For e.g. we own a car showroom and it has some cars, car is represented as an object
of class Car. A showroom contains several cars to represent it we create more than one
beans (objects) for each as shown below.
42 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R
Nagar, Cell. 9246212143. Phone: 040-64512786package com.bi.beans;
Mr. Sriman Spring Framework
Car.java
public class Car {
private int id;
Private String name;
private String engineType;
private String engineModel;
private String classType;
public void setId(int id) {
this.id = id;
3
public void setName(String name) {
this.name = name;
+
public void setEngineType(String engineType) {
this.engineType = engineType;
a
public void setEngineModel(String engineModel) {
this.engineModel = engineModel;
>
public void setClassType(String classType) {
this.classType = classType;
i
1/ override to stri
43 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.%
‘Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
application-context.xml
"com.bi.beans.Car">
In this way if we have 10 cars in the showroom we need to declare 10 beans in the
spring bean configuration file, but if we closely observe all the beans contains the
configuration values as same across. This results out in duplication of configuration.
Rather than declaring the values again in all the beans here we can reuse the
Properties of swifti in swift2 car.
Make the swift2 car inherit from swift1 car so that the values of the swift car will be
copied into swift2 car and we can avoid declaring the properties again as shown below.
application-context.xml
id” value="1"/>
‘engineType" valu
-om.bi.beans.Car* parent="swiftl">
id" value="2"/>
Now the name, engineType, engineModel and classType property values will be copied
from “swift” car so we avoid duplication of configuration.
‘The bean that is being inherited is called parent bean, the bean that is getting inherited
is called child bean of that parent. Always the parent bean property values will be
copied to the child beans.
In the above example, the “swift2” car id will be different from “swift1” car id as every
car has its own id, so “swift2” car has re-declared the value for the id property, it
means the child bean property values will always overwrites the parent bean property
values.
44 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr, Stiman. Spring Framework
In the above example if we observe the “swift1” car is an active bean from which other
cars are inheriting from. If any changes to “swift” car will affect all the other cars as
well. To avoid this we need to take one common base car which will contains common
property values that can be used by all the other classes.
application-context.xml
id” value="2"/>
Now in the above case as baseCar is a dummy bean that is declared to hold common
values that can be reused, we can declare it as abstract bean so that spring will not
create object for it rather it uses its configuration for inheritance.
Few points to remember:
+ When we use bean inheritance, the parent bean and the child bean class types
are not necessary to be same. All the properties of the parent bean must and
should be present in child bean only
+ When we inherit one bean from another bean, only the parent bean property
values will be copied into child bean property values but the physical classes will
never get extended.
‘+ Itis recommended to declare one of the beans as abstract bean which contains
all the common values that should be inherited to the child. As it is an abstract
bean we never modify any property unless it has to be affected to all.
+ When we declare a bean as abstract, the class will not become abstract only the
current bean definition will become abstract, which means spring will not create
the object of that bean. Any call to factory.getBean(“abstractbean”) to an
abstract bean will results out in an error.
45 | OURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
‘Nagar, Cell, 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
package com.
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org. springframework.core.io.ClassPathResource;
import com.bi.beans.Car;
public class BITest {
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new ClassPathResource(
“com/cc/common/application-context.xm!"));,
Car car = factory.getBean("swift1", Car.class);
System.out.printin(car);
>
In the above configuration we declared baseCar as abstract which means spring IOC
container wil! nat instantiate the object for the bean declaration. But it acts as a base
bean from which its property values will be inherited to child beans.
Now when we run the above program, the swift1 car will inherit the values of name,
engineType, engineModel, classType from baseCar.
2.8 Collection Merging
Let us try to understand the collection merging by taking one example, we have a class
Course and it has list of subjects. And we create multiple beans of this class to
represent different courses offered in a college, let’s say btechCS1Yr1Sem and
btechECE1YriSem as shown below.
Course.java
Package com.cm.beans;
import java.util.List;
public class Course {
private List subjects;
public void setSubjects(List subjects) {
this.subjects = subjects;
3
I] override toString() method
46 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman ‘Spring Framework
application-context.xml
‘com.cm.beans.Course">
c
DMS
c
DMS
S.E
Now if you see the above configuration few subjects are common across different
courses even then also we need to re-declare those. Instead of re-declaring them to
reuse we can use bean inheritance. So, now inherit the bTechECE1Yr1Sem bean from
bTechCS1YriSem bean as shown below.
application-context.xml
c
DMS
S.E
Can you guess how many subjects will be there in bTechECE1YriSem bean, it will have
only on that is ‘S.E’! why? Always in case of inheritance the parent bean property value
will be overwritten by child bean property values, so the 'C’ & ‘DMS’ will be overwritten
by‘S.€’ value, But we want the bTechECE1Yr1Sem bean to have all the values
including °C’ & DMS" is it possible? Yes for that you need to use collection merging.
47 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R
‘Nagar, Celt, 9246212343, Phone: 040-64512786Mr. Sriman. Spring Framework
If the parent bean property is a collection type, in the child bean if we have a similar
property of the same collection type, we can merge the values of parent property
collection with the child using collection merging as shown below.
[
49 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Anche Bank Opp: Reebok Show room, S.R
Nagar, Cell, 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
package com.ib.test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xmi.XmiBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.ib.beans.BiCycle;
public class IBTest {
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new ClassPathResource(|
“com/ib/common/application-context.xml"));
Bicycle be = factory.getBean("biCycle”, BiCycle.class);
System.out.printin(be);
+
In the above case If you observe Chain cannot be used independently without @
Bicycle, so why it should have an independent existence?
As no one is going to use Chain and as it is only being used by BiCycle, if we declare
the Chain inside the BiCycle all the related configuration related to BiCycle will be there
at one place and it would be easy to manage and understand the configuration at
single shot.
50 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell, 9246212143. Phone: 04064512786Mr. Sriman. Spring Framework
2.10 Using IDRef
In some cases a bean wants to use the id of another bean, so how to inject "id" of a
‘bean into another bean, here we need'to use IDRef.
For example Car needs an Engine to run, to use Engine inside Car we can inject Engine
into the Car, but I don’t want to inject rather we want to pull, to pull we need the id of
the Engine inside the car. So, we are injecting the “id” of the engine into the Car as
shown below.
car.java
package com.idref.beans;
import org.springframework.beans.factory.BeanFactory;
import org.springfrarnework.beans.factary.xml.XmiBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.idref.beans.Engine;
public class Car {
private String beanid;
public void setBeantd(String beanId) {
this.beanid = beantd;
3
Public void run() {
Engine engine = null,
BeanFactory factory = new XmiBeanFactory(new
ClassPathResource(“com/idref/common/application-context.xml”));
engine = factory.getBean(beanld, Engine.class);
engine.start();
‘System.out.printin(*Running....");
ba
Engin
package com.idref.beans;
public class Engine {
public void start() {
System.out.printin("Started...”);
7
51 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S-R.
Nagar, Cell. 9245212143, Phone: 040-64512786Mr. Sriman Spring Framework
application-context.xm!
package com.idref.test;
import org.springframework.beans.factory.BeanFactory;
port org. springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.idref.beans.Car;
public class IDRefTest {
public static void main(String{] args) {
BeanFactory factory = new XmlBeanFactory(new ClassPathResource(|
"com/idref/common/application-context.xml"));
Car car= factory.getBean("car", Car.class);
‘System.out.printin(car);
+
Will the above program work's? Yes but there is a problem with the above piece of
code. The problem here is we are passing the bean id “engine” as value into the Car, If
the bean id has been changed let's say from “engine” to “enginei” then it would be
difficult to track and change the as the property is configured as value.
+ Developer will not be able to understand upon looking into configuration whether
to modify or not as it looks like a simple value.
+ Spring will try to create the IOC Container even the configuration is in-
consistent, which will results in an runtime exception while getting the Engine
using factory.getBean
To avoid the above problems it is recommended to pass the id of another bean as
value using idref tag. “ref” means referring an object, “idref” means ref to an id of
another bean. Below example that shows the same.
application-context.xmt
52 ] DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell, 9246212143. Phone: 040-64512786Mr. Sriman, Spring Framework
With the above spring while creating the Car bean in the IOC container, it checks is any
bean with id as “engine” exists if found then only creates the car and injects the value
“engine” into the Car. Otherwise will stop creating the object and throws an exception.
2.11 Bean Aliasing
In spring when you configure a class as Bean you will declare an id with which you
want to retrieve it back from the container. Along with id you can attach multiple
names to the beans, and these names acts as alias names with which you can look up
the bean from the container.
Prior to spring 2.0 in order to declare multiple names you need to declare an “name”
attribute at the bean tag level whose value contains bean names separated with ”,”.
Following code snippet shows the same.
package com.ba.beans;
public dass Robot {
private int id;
private String name;
1/ setters
@override
public String tostring() {
return "Robot [id=" + id +", name=" + name +
-
eae
application-context.xml
"com.ba.beans.Robot”>
‘Your can retrieve the above bean with either robot or agent or machine names. You can
even get all the names of the bean using factory.getAliases("onename").
In general bean aliasing is used for ease maintenance of the configuration.
In spring 2.0 a new tag has been introduced
using which you can declare
multiple names for the bean. The syntax is as follows
53 | OURGA SOFTWARE SOLUTIONS, 23/387, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell, 9246212143. Phone: 040-64512786Mr, Sriman Spring Framework
package com.ba.test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.ba.beans.Robot;
public class BATest {
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new ClassPathResource(
"com/ba/common/application-context.xml"));
// this will work as agent is alias name of robot bean
Robot robot= factory.getBean("agent", Robot.class);
System.out.printin(robot);
String{] aliases = factory.getAliases("robot”);
for(String alias : aliases) {
System.out.printin(“alias : “ + alias);
+
+
2.12 Null String
The concept of Null string is how to pass Null Value for a Bean property. Let’s consider
a case where a class has attribute as String or other Object. We are trying to inject the
value of this attribute using Constructor Injection.
In case of constructor injection the dependent object is mandatory to be injected in
configuration, In case if the dependent object is not available, you can pass null for the
dependent object in the target class constructor as shown below.
Motor.java
package com.un.beans;
public class Motor {
private String id;
public Motor(String Id) {
this.id
}
// toString()
154 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
applicat
n-context.xml
If you see the declaration, in order to pass null as value for the dependent object you
need to use the tag ,
package com.un.test;
import org.springframework.beans.factory.BeanFactory;
import org. springframework. beans.factory.xml.XmiBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.un.beans. Motor;
public class UNTest {
public static void main(String[] args) {
BeanFactory factory = new XmIBeanFactory(new ClassPathResource(|
"com/un/commonjapplication-context.xml"));
Motor motor= factory.getBean("motor", Motor.class);
System.out.printin(motor);
With the above the Motor abject will be created by initializing the String id to null,
55 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Barik Opp: Reebok Show room, S.R
‘Nagar, Cell. 9246212143, Phone: 040-64512786Mr, Sriman Spring Framework
2.13 Bean Scopes
In spring when you declare a class as a bean by default the bean will be created under
singleton scope. Before understanding about scopes we need to understand what
singleton class is and when to use it.
What is singleton, when to use.
When we create a class as singleton, it means we have only one instance of the class
within the classloader.
We need to use singleton class in the below scenarios.
3) If a class has absolutely no state then declare those classes as singleton, as the
class doesn’t contains any attributes and it has anly behavior's, calling the
methods with object or object 2 doesn’t makes any difference. So, instead of
floating multiple objects in memory, we can have one object calling any methods
of that class.
2) If a class has some state, but the state is read-only in nature then all the objects
of that class sees the same state, so using the class behavior’s with one object
or n objects doesn’t makes any difference, so we can use only one object of the
class rather than multiple.
3) Ifa class has some state, but the state can be shared across multiple objects of
the class. The state it contains is not only sharable but also it is very huge in
nature, so instead of declaring multiple objects of that class we can allow to
access the shared state through one ebject. But should allow the write/read
access to the state via serialized order (synchronized fashion). For e.g... all the
cache classes has shared state which is shared across multiple objects of that
class, but write/read operations to the cache data will be allowed in a
synchronized manner.
In all the above scenarios we need to declare the class as Singleton. If a class is
inverse of the above principles we should not declare the class as singleton rather
should create multiple instances to access it.
In spring you can declare a bean with 5 different scopes as follows.
1) Singleton - by default every bean declared in the configuration file is defaulted
to singleton (uniess specified explicitly). This indicates when you try to refer the
bean through injection or factory.getBean() the same bean instance will be
returned from the core container.
2) Prototype - When we declare a bean scope as prototype this indicates every
reference to the bean will return a unique instance of it.
56 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bonk Opp: Reebok Show room, S.R
Nagar, Cell, 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
3) Request ~ When we declare a bean scope as request, for every HTTPRequest a
new bean instance will be injected
4) Session - For every new HttpSession, new bean instance will be injected.
5) Global Session - the globalsession scope has been removed from Spring 3.0.
This is used in Spring MVC Portlet framework where if you want to inject a new
bean for a Portal Session you need to use this scope.
By the above it is clear that you can use request and session in case of web
applications. So we will postpone the discussion on these till Spring MVC.
Let’s understand how to use singleton and prototype.
DateUtiljava
package com.bs.beans;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
public String formatDate(Date dt, String pattern) {
String s = null;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);,
's = sdf.format(dt);
return ;
57 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
‘Mager, Cel. 3246247443, Phone: 040-64512786Mr. Sriman Spring Framework
BeanScopeTest.java
package com.ba.test;
import ora. springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.Xm{BeanFactory;
import org. springframework.core.io.ClassPathResource;
import com.bs.beans.DateUtil;
public class BSTest {
public static void main(String[] args) {
BeanFactory factory = new XmiBeanFactory(new ClassPathResource(
“com/bs/common/application-context.xml"));
DateUtil dui = factory.getBean("dateUtil", Datevtil.ciass);
DateUtil du2 = factory.getBean("dateUtil", DateUtil.class);
System.out.printin(du1 == du2);
As in the configuration we declare the dateUtil bean scope as prototype the
comparision between dui == du2 will returns false. If we set the scope as singleton it
will yields to true.
2.14 Bean Autowiring
In spring when you want to inject one bean into another bean, we need to declare the
dependencies between the beans using or tag in the
configuration file, This indicates we need to specify the dependencies between the
beans and spring will reads the declarations and performs injection.
But when it comes to autowiring, instead of we declaring the dependencies we will
instruct spring to automatically detect the dependencies and perform injection between:
them.
So, in order to do this we need to enable autowiring on the target bean into which the
dependent has to be injected. You can enable autowiring in 4 modes.
1) byname ~ If you enable autowiring by name, spring will finds the attribute name
which has setter on the target bean, and finds the bean in configuration whose
name is matching with the attribute name and performs the injection by calling
the setter. Following code demonstrates the same.
558 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, 5.R
Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
Humpty.java
package com.ba.beans;
public class Humpty {
private Dumpty dumpty;
public void setDumpty(Dumpty dumpty) {
System.out.printin("Setter")};
this.dumpty = dumpty;
+
public void showHumpty() {
System.out.printin("l am working with Dumpty
" + dumpty.getName());,
>
a
Dumpty.java
package com,ba.beans;
public class Dumpty {
private String name;
public String getName() {
return name;
Bi
public void setName(String name) {
this.name = name;
3
application-context.xmt
If you see the above configuration, on the humpty we enabled autowire byName. With
this configuration, it will tries to find the Humpty beans attributes which has setters,
with that attribute name “dumpty” it will tries to find a relevant bean with the same
name “dumpty” as the bean is available it will injects the dumpty bean into Humty
attribute. :
2) byType ~ If we enable autowire byTybe, if will find the attributes type in the
target class and tries to identify a bean from the configuration file of the same
type and then injects into target class by calling setter on top of it. Below
configuration demonstrates the same.
59 | DURGA SOFTWARE SOLUTIONS, 23/3R7, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143. Phone: 040-64512786Mr, Sriman. Spring Framework
application-context.xml
|
In the above case the bean attribute name is “dumpty”, and in the configuration the
bean name is “dumpty12” even though the names are not matching still the dumpty12
bean will be injected into humpty. Because the type of the attribute and the bean type
is matching.
Note:- if multiple bean declarations of the same type is found it will throw an ambiguity
error without instantiating the core container.
3) Constructor ~ If we enable autowire in constructor mode, now it will tries to find
a bean whose class type is same as constructor parameter type, if a matching
constructor is found it will passes the bean reference to its constructor and
performs injection. This means it is similar to byType but instead of calling setter
it will call constructor to perform injection.
Humpty java
package com.ba.beans;
Public class Humpty {
private Dumpty dumpty;
public Humpty() {
super();
>
Public Humpty(Dumpty dumpty) {
‘System.out.printin("Constructor’
this.dumpty = dumpty;
+
public void showHumpty()
System.out.printIn("I am working with Dumpty
+
+ dumpty.getName());,
There is no change in configuration apart from declaring on the bean
autowire="constructor”
4) Autodetect - this has been removed from spring 3.0 onwards as it is quite
confusing, In this it will tries to perform injection by finding a relevant
constructor by type if not found then it will finds the setter by type and performs
injection.
60 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr, Sriman Spring Framework
Drawback with autowiring ~ The problem with autowiring is we don't have control over
which beans has to get injected into what, so it is least recommended to use
autowiring for a large applications. For pilot projects where RAPID application
development is needed we use autowiring.
2,15 Nested BeanFactories
If we have two bean factories in an application, we can nest one bean factory into
another to allow the beans in one bean factory to refer to the beans of other factory. In
this we declare one bean factory as parent bean factory and will declare the other as
child.
This is similar to the concept of base class and derived classes. Derived class can.
access the attributes of base class, but base class cannot access the attributes of
derived class.
In the same way child bean factory beans can refer to the parent bean factory beans,
But parent bean factory beans cannot refer to child beans declared in child factory.
Pictorial representation of it is shown below.
Below example shows how to use it.
EMICalculator.java
package com.nbf.beans;
public class EMICalculator {
public float compute(long principai, float rateOfinterest, int years) {
return 343.341;
ae
61 | DURGA SOFTWARE SOLUTIONS, 23/3RT, tear Andhre Bank Opp: Reebok Shaw roam, S.R
Nagar, Cell, 9246212143, Phone: 040-64512786,Mr. Sriman Spring Framework
CustomerLoanApprover.java
package com.nbf.beans;
public class CustomerLoanApprover {
private EMICalculator emiCalcutator;
public void approve(double grossSalary, long principalAmount, int years) {
float emi = emiCalculator.compute(principalAmount, 13.5f, years);
System.out.printin("Emi : " + emi);
if (emi > 0) {
‘System.out.printin("Approved");
} else {
System.out.printin("Rejected");
+
+
public void setEmiCalculator(EMICalculator emiCalculator) {
this.emiCalculator = emiCalculator;
3
>
If the EMICalculator class has been declared in one configuration file and
‘CustomerLoanApprover class has been declared in second configuration file. In order to
inject EMICalculator into CustomerLoanApprover class we need to nest their factories
as shown below.
loan-beans.xml
|
customer-beans.xml
[
In the above configuration in order for your bean declaration to refer to parent beans,
has to use the tag . Apart from parent attribute it has local which
\dicates refer to the local bean. Along with it we have bean attribute as well, which
indicates look in local if not found the search in parent factory and perform injection.
62 | DURGA SoFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
NBFTest.java
public static void main(String[] args) {
BeanFactory pf = new XmiBeanFactory(new ClassPathResource(
“com/nbf/common/loan-beans.xml"));
BeanFactory cf = new XmiBeanFactory(new ClassPathResource(
"com/nbt/common/customer-beans.xml"), pf);
CustomerLoanApprover cla = cf.getBean("customerLoanApprover",
‘CustomerLoanApprover.class);
cla.approve(3423.3f, 3535, 324);
If you observe the above code while creating the "cf" factory we passed the reference
of “pf” to create it. This indicates “cf” factory has been nested fram “pf”.
This completes the Spring Core basic concepts and enables us to proceed for advanced
spring core concepts.
63 | ourGa SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R
‘Nava, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
3 Spring Core (Advanced)
3.1 Using P & C ~ Namespace
If we want to perform setter injection on a spring bean we need to use
tag. Instead of writing length tag declaration under the tag, we
can replace with short form of representing the same with p-namespace.
In order to use the p-namespace, you first need to import the
“http://www.springframework.org/schema/p” namespace in the spring bean
configuration file. Once you have imported it, you have to write the attribute at the
tag level to perform the injection as p:propertyname="value” or
p:propertyname-ref="refbean”.
C-Namespace has been introduced in spring 3.1.1, in order to perform constructor
injection we need to use tag. Instead of writing the length
tag, we can replace it with c-namespace. The syritax for writing the
C-Namespace is c:argument="value” or c:-argument-ref="refbean”
Course.java
Package com.pnamespace.beans;
public class Course {
private int id;
private String name;
Public int getd() {
return id;
+
public void setId(int id) {
this.id = id;
+
public String getName() {
return name;
+
public void setName(String name) {
this.name = name;
>
64 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Renbok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
Person,java
package com.pnamespace. beans;
public class Person {
private Course course;
public Person(Course course) {
this.course = course;
+
public void whichCourse() {
System.out.printin("Course : " + course.getName());
application-context.xml
1.0" encoding="UTF-8"2>
'nttp://www.springframework,org/schema/beans”
"hittp:/ /wvsw.w3.0rg/2001/XMLSchema-instance"
http://www.springframework.org/schema/c”
“http: / / www.springframework.org/schema/ Pp"
xsi: schemaLocation="http: //www.springframework.org/schema/beans,
http://www.springframework.org/schema/beans/spring-beans.xsd">
34”
‘com.pnamespace.beans.Person”
‘course-
3.2 Dependency Check
In case of constructor injection, all the dependent objects are mandatory to be passed
via tag while declaring the bean, but in case of setter injection the
dependent objects are not mandatory to be injected. So, if want setter properties
mandatory like similar to constructor properties then we need to use Dependency
Check.
Dependency check has been removed from Spring 2.5. From spring 2.5 it has been
replaced with @Required annotation, we will discuss about it in spring annotations
support.
In order to perform the mandatory check on setter properties you need to enable
dependency check. In order to enable dependency check you have to write the
attribute dependency-check=”"mode”. Dependency check can be enabled in three
modes.
65 | OURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
1) Simple - when you turn the dependency check in simple mode, it will check all
the primitive attributes of your bean (attributes contains setters) whether those
has been configured with values in configuration file. If any primitive attribute is
not configured with or p-namespace in configuration automatically
the core container will detects and throws error without creating the container.
2) Object- when you turn on the dependency check in object mode, it will check all
the Object type attributes on your target class whether those has been
configured the property inj configuration, if not will throw exception as
said above.
3) all - when you turn on the dependency check as all mode, it will check for both
sitnple and objects types of your class attributes, if those values are not injected
through configuration it will throw exception.
Refer the example for the same.
Engine.java
package com.de.beans;
public class Engine {
private int id;
private String name;
public int getId() {
return id;
a
Public void setId(int id) {
this.id = id;
-
Public String getName) {
return name;
+
public void setName(String name) {
this.name = name;
>
66 | OURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, 5.R
‘Nagar, Cell, 9246212143. Phoné: 040-64512786Mr. Sriman Spring Framework
Motor,java
package com.de.beans;
public class Motor {
private Engine engine;
public void setEngine(Engine engine) {
this.engine = engine;
+
public void runt) £
‘System.out.printin("Running with engine : " + engine.getName());
y
application-context.xml
‘
‘com.dc.beans.Motor" dependency-check="objects">
“engine” ref="engine"/>
The main drawback with dependency check is you don’t have control on which attribute
should be made as mandatory and which is optional, either you can the dependency
check at simple level or object or all.
3.3 Depends-on
If a class uses the functionality of other class inside it, then those classes are directly
dependent on each other. But every class may not directly dependent on other;
sometimes there may be indirect dependency. Let us consider a use case to
understand,
We have a class LoanCalculator, it has a method callnst to it we pass principle,
noofmonths and city name as input. When we call this method it should find the
applicable rate of interest for the city we passed by fetching it from properties file.
67 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143. Phone: 040-64512786Mr, Sriman Spring Framework
package com.don.beans;
import java.util.Properties;
public dass LoanCalculator {
Public double cafinst(Long principle, int n, String city) throws Exception {|
float ri = 0.0F;
double amt = 0.05;
Properties cityInsProps = null;
/f read the data from properties file
// \oad into properties collection
// now find the rate of interest for the given city
amt = (principle * n * rf) / 100;
return amt;
The problem with above code is we will read the same data repeatedly for every call to
the callns method of the LoanCalculator class.
So instead we want to cache the data so that the LoanCalculator now can go and get
the data from cache, So for this when we call calins method we will check whether the
data is avaitabfe with cache or not. If it is not available we will read the city and rate of
Interest values from properties file as key and values and place in properties collection.
Now we will store this properties collection into the Cache as shown below. As now the
data is available in cache we can pull the data from Cache itself.
package com.don.beans;
Public class LoanCalculator {
Public double callnst(Long principle, int n, String city) throws Exception {|
float ri = 0.0F;
doubie amt = '0.0f;
Cache cache = null;
Properties cityInsProps = null;
cache = Cache.getinstance();
if (cache,containsKey("cityRI") == false) {
// read the data from properties file
J make it as properties collection
// store in the cache with key as "cityRI”
cityinsProps = cache.get(“cityRI");
Ti = Float.parseFloat(cityinsProps.getProperty(city));
amt = (principle * n * ri) / 100;
return amt}
68 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Shaw room, $.R.
Magar, Cell. 9246212143. Phone: 040-64512766Mr. Sriman Spring Framework
Is there any problem in the above piece of logic, yes the problem is here the city and
rate of interest values may not only required for LoanCalculator there may be several
other classes in the application want to read the data from Cache. So, we need to write
the logic for checking the data is available in the cache if not load the data into cache
and use it.
So, we end up in duplicating the same logic across various places in the application.
Instead can we write the logic for populating the data into cache in cache constructor?
Yes it seems a good idea because constructor of the cache will be called only once as it
is singleton and we need to read the data only once, the better place to write the logic
for populating is in constructor of the class as shown below.
package cam.don, beans;
public class LoanCalculator {
public double callnst(Long principle, int n, String city) throws Exception {
float ri = 0.08;
double amt ='0.0F;
Cache cache = null;
Properties cityInsProps = null;
cache = Cache.getInstance();
cityInsProps = (Properties) cache.get("cityRI");
if (citylnsProps == null) {
throw new Exception("Internal error");
=
if (cityinsProps.containsKey(city) == false) {
throw new Exception("City not valid");
y
ri = Float.parseFloat(cityInsProps.getProperty(city));
amt = (principle * n * A) / 100;
return amt;
69 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Anchra Bank Opp: Reebok Show room, S.R.
Slagar, Cel. 9246212543. Phone: 060-64512786Mr, Sriman, Spring Framework
package com.don.util;
public class Cache {
private Map dataMap;
public Cache() {
dataMap = new HashMap();
/| write the logic for reading the data from properties file
71 put that into properties collection
// and store it into dataMap
a
Public void put(String key, Object val) {
dataMap.put(key, val);
}
Public Object get(String key) {
return dataMap.get(key);
:
Public boolean containskey(String key) {
return dataMap.containsKey(key);
}
>
Is there any problem with the above code, yes? Here the cache is exposed to the
details of the source from where the data is coming from. Due to which any changes to
the underlying source again will affect the cache.
Instead we should never write the logic for populating the data into cache rather we
should write that logic in separate class called CacheManager. CacheManager is the one
responsible for reading the data from underlying source system and massaging the
data and storing the data into Cache.
package com.don.util;
public class CacheManager {
public CacheManager() {
init;
Public void init) {
Cache cache = null;
cache = Cache.getInstance();
// read the data and populate into cach
Again is there any problem with above code? Yes, as the data comes from severat
source systems again we will write multiple access related Jogic in one single class. This
may become complicated and difficult to manage and modify.
70 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell, 9246212143, Phone: 040-64512786Mr. Sriman, Spring Framework
Instead write the logic for reading the data from source system in Accessor class. Now’
CacheManager will talk to Accessors in retrieving the data and populating into cache.
Now if we observe LoanCalculator is dependent on Cache or CacheManager to read the
data. LoanCalculatar never talks to CacheManager rather it reads the data from Cache.
But inorder to populate the data into Cache, the CacheManager should be created first
than LoanCalculator.
So here the LoanCalculator and CacheManager are indirectly dependent on each other.
Before the LoanCalculator gets created, always the CacheManager has to be created
first. This is called creational dependencies these can be managed using depends on as
shown below,
Package com.don.util;
‘Import java.util.Map;
import com.don.accessor.JAccessor;
public class CacheManager {
private Cache cache;
Private Map accessorMap;
Public CacheManager(Cache cache, Map accessorMap) {
this.cache = cache;
this.accessorMap = accessorMap;
init();
Public void init() {
Object data = null;
Accessor accessor = null;
for (String dataKey : accessorMap.keySet()) {
accessor = accessorMap.get(datakey);
data = accessor.getData();
cache.put(datakey, data);
71 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R.
Nagar, Cell. 9246212143. Phone: 040-64512786Mr, Sriman Spring Framework
package com.don.utily
import java.util. HashMap;
import java.util.Map;
public class Cache {
private Map dataMap;
public Cache() {
dataMap = new HashMap();
7
public void put(String key, Object val) {
dataMap.put(key, val);
y
public Object get(String key) {
return dataMap.get(key);
3
public boolean containsKey(String key) {
return dataMap.containskey(key);
}
>
package com.don.accessor;
public interface IAccessor {
package com.don.accessor,
import java.util. Properties;
import java.util.ResourceBundle;
public dass CityInterestAccessor implements IAccessor {
Object getData();
@Override
public Object getData() {
ResourceBundle rb = null;
Properties props = null;
rb = ResourceBundle.getBundle("com/don/common/cityins");
props = new Properties();
for (String key : rb.keySet()) {
rops.put(key, rb.getString(key));
Feturn props;
72 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, SR
Nagar, Cell, 9246212143. Phone: 04064512786Mr. Sriman. Spring Framework
Package com.don.beans;
import java.util.Properties;
Import com.don,util.Cache;
Public class LoanCalculator {
private Cache cache;
public double calinst(Long principle, int n, String city) throws Exception {
float ri = 0.01
double amt = 0.0F;
Properties cityInsProps = null;
cityInsProps = (Properties) cache.get("cityRI”)
if (cityInsProps == null) ¢
‘throw’ new Exception("Internal error”
if (citylnsProps.containskey(city) == false) {
throw new Exception("City not valid");
ri = Float.parseFloat(cityinsProps.getProperty(city));
amt = (principle * n * ri) / 100;
return amt;
Public vold setCache(Cache cache) {
this.cache = cache;
+
+
3.10 Lookup Method Injection
In spring when a non-singleton bean is getting injected into a singleton bean the result
will be always singleton. For example if LoanApprover is a singleton class and Loaninfo
is a non-singleton class. If we inject Loaninfo into LoanApprover class as shown below.
loaninfo"/>
‘prototype"/>
As the loanApprover is a singleton class, only one object of LoanApprover will be
created by core container and hence Loaninfo bean will be injected once via setter
injection into LoanApprover class. This leads to Loaninfo as singleton.
Ideally speaking the above design is wrong, because if we want to declare a class as
singleton, it should not contain any state. As the LoanApprover is using the Loaninfo,
instead of injecting Loadinfo via setter or constructor injection, LoanApprover has to
fetch the LoanInfo from the container and should use and dispose it.
The below table depicts the matrix of combinations of single-ton and non-singleton.
HuBeaMpRESU
Singleton v
Singleton | Non-Singleton x
(Should not use setter or constructor,
use lookup method injection)
Non-Singleton | Singleton v
Non-Singleton | Non-Singleton v
DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R
Nagar, Cell. 9246212143, Phone: 040-64512786
cacti can anicasims-ememnen ee aimeeMr. Sriman. Spring Framework
Let's try to understand this better by taking one more example. The Web container
upon receiving a request from the client, it will try to process the request by creating a
new Object of RequestHandler class and populates the request data to RequestHandler,
If you observer the above scenario, here the Web container is a singleton class and
RequestHandler is a non-singleton class, far every incoming request to the container it
has to create a new RequestHandler class object and popuiate the request info and
then should handover the control to process the request. So, the Web container will
fetch the RequestHandier (50 that each lookup of request handler will returns new
object) class object upon receiving the request and populates data to process.
The Web Container class can fetch the Object of RequestHandler by implement
BeanFactoryAware and can call getBean method to get the RequestHandler object
shown below.
package com.Imi.beans;
public class WebContainer implements BeanFactoryAware {
private BeanFactory factory;
public void process(String data) {
RequestHandler rh = factory.getBean("requestHandler”,
RequestHandler.class);
rh.setData(data);
th.handle();
+
public Void setBeanFactory(BeanFactory factory) {
ha
this.factory = factory;
In the above code we have used factory.getBean("requestHandler”), this indicates that
we have hardcoded the logical name of the bean in our code, so that our code is tightly
coupled with that specific bean. Second issue with that code is we have implemented
‘our code from spring specific interface which indicates we lose the benefit of non-
invasive feature of spring.
To avoid the above problems we need to use Lookup Method Injection. In this your
class doesn’t need to implement from any spring specific class or interface, You don’t
need to code for getting the reference of dependent object. Instead you deciare to
spring asking it to write the code of getting the dependent object through
configuration, so that your code is loosely coupied with a spring bean. This is shown in
the below example.
93 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, 5.8
Nagar, Cell, 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
WebContainer.java
package com.Imi.beans;
abstract public class WebContainer {
Public void process(String data) {
RequestHandler rh = getRequestHandler();
rh.setData(data);
thhandle();
abstract public RequestHandler getRequestHandler();
+
RequestHandler.java
package com.Imi.beans;
Public class RequestHandler {
Private String data;
Public void setData(String data) {
this.data = data;
oe
public void handle() {
‘System.out.printin(*Processing request with data : “ + data);
+
In the above code we declared a method getRequestHandler() as a abstract method
which returns RequestHandler object. We don’t know how to write the logic in this
method to get the RequestHandler object, so we declared this as abstract asking spring
to implement this method for us. We will tell spring to implement the
getRequestHandler method in configuration as shown below.
application-context.xml
:
package com.pe.test;
import org. springframework.beans.factory.BeanFactory;
import org. springframework.beans.factory.xml.XmiBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.pe.beans.Payslip;
public dass PETest {
Public static void main(String[] args) {
BeanFactory factory = new XmiBeanFactory(new ClassPathResource(
‘Nagar, Cell. 9246212143. Phone: 040-64512786
“com/pe/common/application-context.xmI"));,
Payslip ps = factory.getBean("payslip", Payslip.class);
‘System, out.printin(ps);
+
me |
‘As we understood the purpose of PropertyEditor, let’s try to understand how to create ©
‘our own custom property editor by taking an example.
| 96 { DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, §.RMr. Sriman.
ComplexNumber.java
package com,pe.beans;
Public class ComplexNumber {
private int base;
private int expo;
public ComplexNumber(int base, int expo) {
this.base = base;
this.expo = expo;
>
public int getBase() {
return base;
3
public void setBase(int base) {
this.base = base;
y
public int getExpo() {
return expo;
+
public void setExpo(int expo) {
this.expo = expo;
,
MathCalculator.java
Spring Framework
package com.pe.beans;
public class MathCalculator {
private ComplexNumber complexNumber;
public void setComplexNumber(ComplexNumber complexNumber) {
this.complexNumber = complexNumber;
>
public void calculate() {
‘System.out.printin("Calculating with complex number base : "
+ complexNumber.getBase() +” expo : "
+ complexNumber.getExpo());
In order to inject ComplexNumber into MathCalculator, the configuration looks as
follows.
97 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143. Phone: 040-64512766Mr. Sriman Spring Framework
application-context.xml
‘
The above configuration works without any issue, but instead of configuring the
‘complexNumber as a bean and injecting via property reference, we want to configure
the complexNumber as a String literal value as 24, 34 where 24 is the base and 34 is
the expo as shown below.
In order to achieve the above, we need to write a custom property editor which will
reads the string value “23, 34” in the configuration and coverts it to the target class
attribute type, in this case ComplexNumber type and injects it.
So, to develop a custom property editor you need to write a class which extends from
PropertyEditorSupport and should register this with the BeanFactory as shown below.
ComplexNumberEditor.java
Package com.pe.beans;
import java.beans.PropertyEditorSupport;
Public class ComplexNumberEditor extends PropertyEditorSupport {
@Override
public void setAsText(String value) throws IllegalArgumentException {
int base = 0;
int expo =
base = Integer.parseInt(value:substring(0, value.indexOf(",")));
‘expo = Integer.parseInt(value.substring(value.indexOf(",") + 1,
value.length()));
ComplexNumber complexNumber = new ComplexNumber(base, expo);
‘setValue(complexNumber);
98 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
After developing a custom property editor class, you need to register this with the
BeanFactory after creating the factory shown below.
PETest.java
package com.pe.test;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework. beans.PropertyEditorRegistry;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org-springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import com.pe.beans.ComplexNumber;
import com.pe.beans.ComplexNumberEditor,
import com-pe-beans.MathCalculator;
public class PETest {
public static void main(String} args) {
BeanFactory factory = new XmlBeanFactory(new ClassPathResource(
“comn/pe/common/application-context.xml"));
((ConfigurableistabieBeanFactory) factory)
.addPropertyEditorRegistrar(new
@override
Public void registerCustomEditors(
PropertyEditorRegistry registry) {
registry.registerCustomEditor(ComplexNumber.class,
new ComplexNumberEditor());
=
»
MathCalculator me = factory.getBean("mathCalculator",
MathCalculator.class);,
mc.calculate();
+
So, after creating the Custom Property editor we need to register that with the.
PropertyEditorRegistry. PropertyEditorRegistry is an intesnal abject in the IOC container
50 we wrote a class implementing PropertyEditorRegistrar and overridden the method.
We registered the PropertyEditorRegistrar as a registrar to the container.
So, container will automatically class the registerCustome€ditors by passing the
registry using which we can register our custorn property editors.
99 | DURGA SOFTWARE SOLUTIONS, 23/2R, Hear Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman, Spring Framework
3.12 Internationalization (i18n)
Internationalization is the process of designing the application to adapt and display the
content specific to the locale from which the user is accessing from.
JEE has support for designing internationalized applications. It has provided a class
“ResourceBundle”, it takes the base bundle name and locale and retrieves the values
from the locale specific property files,
Here is the sample snipped of code showing the same.
messages.properties
HOME_WELCOME_MSG=Welcome to my application
messages_cn_CH.properties
HOME_WELCOME_MSG= isis 3401081
We created two properties file with key as HOME_WELCOME_MSG one containing value
‘as English and other one in Chinese language. Now based on the locale from which the
user is accessing we will pull the value from appropriate locale specific bundle and
display as part of application as shown below.
ResourceBundle rb = ResourceBundle.getBundle("messages", Locale.geDefault());
‘String message = rb.getMessage("HOME_WELCOME_MSG");
[System.out.printin(message);
There are lots of problems with JEE approach in working with Internationalization as
described below.
+ To display content in a Jsp page we should not hardcode rather should read the
text from Message Bundles (properties) files and should display the content. This
means we have to create the “ResourceBundle” object across the servlet’s and ~
should make it available to the Jsp by binding to request scope. But with this we
end up in writing the code across all the classes of our application, instead we
can write a filter which creates the "ResourceBundle” and make it available for
all the requests. This indicates programmer has to decide the strategy of using
the ResourceBundle object in the application.
+ An application cannot be completed with one properties file, we may need to
externalize the values across multiple properties files. If we have multiple
properties file we need to create one ResourceBundle object per Properties file to
read the values. This leads to referring multiple ResourceBundle objects across
the application to retrieve values from different properties files.
+ Sometimes in an application we want to read the value for a key in multiple
Locale bundles. To read the same message in different languages, we need to
create one ResourceBundle object per locale. In this case also we have to refer
more ResourceBundle objects in application.
Spring has a better support for internationalization when compared with JEE
internationalization. It has provided multiple classes like StaticMessageBundleSource,
ResourceBundleMessageSource and ReloadableMessageSource. These take multiple
properties files as inputs and will retrieve the messages from various properties.
100 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.
agar, Cell. 9246212143. Phone: 04064512786Mr, Sriman Spring Framework
‘As we are going to configure this as a bean, by default it is singleton, so for entire
application we will have only one object of this, And these classes has a method
getMessage and it takes the “key” and Locale as a parameter. This indicates the
message can be read from different locales without creating multiple objects.
Now instead of directly reading the messages from these classes we can read the
messages from ApplicationContext as well. This is one of the differences between
ApplicationContext and BeanFactory. BeanFactory doesn’t have internationalization,
support only ApplicationContext has.
Spring has provided methods to access the messages from the resource bundle in
ApplicationContext. Now we can call convienent method getMessage() on application
context in turn reads the messages using the help of the above mentioned classes.
In the ApplicationContext, it declared an attribute messageSource of type
ResourceBundleMessageSource as shown below.
So In order to load properties file you need to declare a bean whose type is
ResourceBundleMessageSource, it will takes an attribute baseName, for which you
need to pass the name of the properties file. This bean has to be named with
messageSource so that when we call getMessage() method on ApplicationContext, it
delegates the call to the bean whose name is "messageSource” to get the messages.
Note: - You have to place the properties file under classes’ folder (place it in src, will
automatically shipped as part of classes).
application-context.xml
class="org.springframework.context.support.ResourceBundleMessageSource">
T18NTestjava
package com.i18n.test;
import java.util.Locale;
import org.springframework.context. ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class I18NTest {
Public static void main(String{} args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
com/il8n/common/application-context.xml");
System. out.printin("Message : *
+ context.getMessage("empid.label", new Objectl] {"is not”,
“valid"}, Locale.getDefault()));
3
3
101 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R
Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
3.13 Bean Post Processor
In spring, we use Bean Lifecycle to perform initialization on a bean. But using init-
method, destroy-method or initializingBean, DisposableBean we do initialization or
destruction process for a specific bean which implement these.
If we have a common initialization process which has to be applied across all the beans
in the configuration, Bean lifecycle cannot handle this. We need to use
BeanPostProcessor.
BeanPostProcessor has two methods postProcessBeforelnitialization and
postProcessAfterInitialization, these methods will be invoked for all the beans on the
core container. postProcessBeforeinitialization method will be called after the core
container has created the bean and before it performs injection.
postProcessAfterInitialization method will be called after the core container has
perfomed injections. For both of these methods the bean will be passed as parameter
along with beanName on which the methods are fired.
In these methods the developer can write the Initialization logic to initialize the beans.
So, you need to write a class which implements from BeanPostProcessor interface and
‘override the methods and provide the logic for initialization, The same has been
depicted in the below example.
EmployeeDelegate.java
package com.bpp.beans;
abstract public class EmployeeDelegate {
private EmployeeVO employeeVO;
Private EmployeeDao employeeDao;
pul
void insert() €
employeeVO = lookupEmployeeVo();
employeeVO.setEmpID("E32542");
employeeVO.setName(“John");
employeeVO.setSalary(353.34f);
‘employeeDao.insert(employeeVO);
+
public abstract EmployeeVO lookupEmplayeeVO();
public void setEmployeeDao(EmployeeDao employeeDao) {
this.employeeDao = employeeDao;
102 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
‘Nagar, Cell, 9246212143, Phoné: 040-64512786Mr. Sriman.
EmployeeDao.java
package com.bpp.beans;
Public class EmployeeDao {
Public void insert(EmployeeVO employeeV0) {
System.out.printin("inserting employee : "
+ employeeVO.getLastModifiedDate());
Employeevo.java
package com.bpp.beans;
public class EmployeeVO extends BaseVO {
private String empID;
private String name;
private float salary;
// setters and getters
>
BaseVO,java
package com.bpp.beans;
Ienport java.util.Date;
abstract public class BaseVO {
private Date lastModifiedDate;
public Date getiastModifiedDate() {
return lastModifiedDate;
i
public void setLastModifiedDate(Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
+
103 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R
Nagar, Cell. 9246212143, Phone: 040-64512786
Spring Framework
faeMr. Stiman Spring Framework
BaseVOBeanPostProcesso:
package com.bpp.beans;
import java.util.Date;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class BaseVOPostProcessor implements BeanPostProcessor {
@override
public Object postProcessAfterinitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof BaseVO) {
‘((BaseVO) bean).setLastModifiedDate(new Date());
return bean;
i
@override
public Object postProcessBeforelnitialization(Object argO, String arg1)
throws BeansException {
return argQ;
application-context.xml
‘Once you create the BeanPostProcessor class, you need to register the postprocessor
with the bean factory as shown below.
104 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell, 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
BPPTestjava
Package com.bpp. test;
import org.springframework,beans.factory.BeanFactory;
port org.springframework. beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.xml.XmiBeanFactory;
iport org. springframework,core.io.ClassPathResource;
import com. bpp.beans.BaseVOPostProcessor;
import com. bpp. beans.EmployeeDelegate;
public class BPPTest {
public static void main(String{] args) {
BeanFactory factory = new XmiBeanFactory(new ClassPathResource(
"com/bpp/common/application-context.xml"));
BaseVOPostProcessor bpp = factory.getBean("bpp",
BaseVOPostProcessor.class);
({ConfigurableListableBeanFactory)
factory).addBeanPostProcessor(bpp);
EmployeeDelegate ed = factory.getBean("employeeDelegate”,
EmployeeDelegate.class);
ed.insert();
So, in the above code after registering the bean postprocessor, when you try to fetch
the EmployeeDelegate bean from the core container, while creating the delegate it will
ty to create EmplayeeVO and EmployeeDa0 to inject into it.
So after the container creates these before performing injection it will call the
postProcessBeforelnitialization and after performing the injection, it will call
PostProcessAfterInitialization,
105 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R.
Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
3.14 Bean Factory Post Processor
If we want to perform some post processing on the BeanFactory after it has been
created and before it instantiates the beans then we need to go for
BeanFactoryPostProcessor.
If we want to change the configuration, we can always change it by modifying the
physical configuration file, Instead if want to modify the configuration dynamically at
runtime within the IOC container metadata then we can use BeanFactoryPostProcessor.
There are many benefits of using BeanFactoryPostProcessors. We can modify the
configuration during the deployment time by using some build tools like ant, But if we
want to modify the configuration again it demands the rebuild and redeployment.
Instead if we go for BeanFactoryPostProcessor as the configuration is modified in the
IOC container metada at runtime.
If we want to perform post initialization after creating the BeanFactory and before
creating the beans, we need to use BeanFactoryPostProcessor. It’s a one of the kind of
extension hooks that spring has provided to the developer to perform customizations
‘on the configuration that is loaded by the Factory.
Spring has provided built-in BeanFactoryPostProcessor's to perform post processing,
based on the type of post processor you use, you will get the respective behavior in
your application. One of it is PropertyPlaceHolderConfigurer.
PropertyPlaceHolderConfigurer is a post processor which will reads the messages from
the properties file and replaces the §{} place holder’s of a bean configuration after the
BeanFactory has loaded it.
ConnectionManager.java
Package com.bfpp.beans;
public class ConnectionManager {
private String url;
private String userName;
Private String password,
// setters & getters
application-context.xml
:
'userName” value="${db.un}"/>
‘password" value="${db.pwd}"/>
106 | OURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, $.R
Nagar, Cell. 9246212143, Phone: 04064512786Mr. Sriman Spring Framework
If you create a BeanFactory with the above configuration, the ConnectionManager bean
will gets created with url, username and password with ${} token values. Instead of
this, if we want to replace the ${} values with property file key values, we need to.
configure PropertyPlaceHolderConfigurer. This post processor after loading the
configuration by BeanFactory and before the factory creates the ConnectionManager
bean, will replaces the ${} values with property key values as shown below.
db.properties
db.url=jdbc:odbc:thin@1521:XE
db.un=weblogic
db.pwd=welcome1
Adding to the above configuration, you need to configure the post processor and
register this with the BeanFactory,
|
BFPPTest.java
package com.bfpp.test;
Import org.springframework.beans.factory. BeanFacto
import org.springframework, beans.factory.config.BeanFactoryPostProcessor;
import org. springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.spring framework. beans.factory. xml.XmiBeanFactory;
1port org. springframework.care.io.ClassPathResource;
import com.bfpp.beans.ConnectionManager;
public class BFPPTest {
Public static void main(Stringf] args) (
BeanFactory factory = new XmlBeanFactory(new ClassPathResource(
“com/bfpp/common/application-context.xml"));
BeanFactoryPostProcessor bfpp = factory.getBean("pphc",
BeanFactoryPostProcessor. class);
bpp. postProcessBeanFactory((ConfigurableListableBeanFactory factory);
ConnectionManager cm = factory.getBean("connectionManager”,
ConnectionManager.class);
System. out.println("em.url : * + m.getUN());
+
107 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Shaw room, S.R
‘Nagar, Cell. 9246212143. Phone: 040-64512785
hii ich lmapai ea imc ice nemaiininanacniSMr. Sriman. Spring Framework
3.15 Event Processing
Spring provides Event handling capabilities using the ApplicationContext. For any event
based processing technic we have four actors, 1) source 2) event 3) event listener and
4) event handler.
Source Is the actor who raises an Event, Event is the class which contains the data
representing the purpose of the event. Listener is the person who will listens for the
event, and upon raising the event by source, listener will catches it and raises a
method call on the handler to process that event.
So, Event handling is used for asynchronous processing, in spring an Event is
represented with ApplicationEvent, Listener is created using ApplicationListener, and
the application listener will contains the method onApplicationEvent() which will be
fired upon raising the Event. In order to publish an event, the source needs an
ApplicationEventPublisher. The below example shows the same.
RefreshEventjava
package com.ep.beans;
import org.springframework.context.ApplicationEvent;
public class RefreshEvent extends AppiicationEvent {
Private String tableName;
Public RefreshEvent( Object source, String tableName) {
‘super(source);
this.tableName = tableName;
d
Public String getTableName() {
return tableName;
+
108 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman, Spring Framework
RefreshEventListener.java
package com.ep.beans;
import org.springframework.context.ApplicationListener;
public class RefreshEventListener implements ApplicationListener {
@Override
public void onApplicationEvent(RefreshEvent event) {
System.out.printin("Refreshing table : " + event.getTableName());
>
3
RefreshEventSource.java
package com.ep.beans;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.applicationEventPublisherAware;
public class RefreshEventSource implements Application€ventPublisherAware {
private ApplicationEventPublisher publisher;
public void raiseRefresh(String table) {
publisher nublishEvent(new RefreshEvent(this, table);
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
3
application-context.xml
109 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Wager, Cell, 9246212143. Phone: 040-64512786Mr. Sriman
EPTest.java
Spring Framework
package com.ep.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ep.beans.RefreshEventSource;
public class EPTest {
Public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"com/ep/common/application-context.xm!");
RefreshEventSource res = context.getBean("refreshEventSource",
RefreshEventSource.class);
res.raiseRefresh("TBLEMPLOYEE");
3.16 Bean Factory VS Application Context
Bean Factory
tion Context
+ Bean Factory is a lazy initializer, this
means after creating the Bean Factory,
it will loads the configuration file but
will not create any beans for the bean
declarations. When you try to fetch the
bean by using factory.getBean(""),
Bean Factory will creates the bean.
+ Bean Factory doesn’t support
Internationalization,
+ Bean Factory doesn't supports Event
Handling and Event processing
+ Bean Factory will not automatically
registers BeanPastProcessors or
BeanFactoryPostProcessors, ‘we need to
explicitly write the code for registering
them.
+ ApplicationContext is an eager
initializer. When you first create the
application context with the
configuration, after loading the
configuration, it will immediately create
all the beans in the configuration.
+ Application Context supports
internationalization.
+ Application Context supports Event
processing.
‘+ Application Context up seeing the
BeanPostProcessor and
BeanFactoryPostProcessor dectarations
in the configuration, will automatically
registers them with the container and
applies processing,
110 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212343, Phone: 040-64512786,Mr. Sriman Spring Framework
111 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show.room, $.R.
Nagar, Cell, 9246212143, Phone: 040-64512786Mr. Sriman
Spring
Spring Framework
Annotation
112 | OURGA SOFTWARE SOLUTIONS, 22/387, Near Andhra Bank Opp: Reebok Show room, &.R
| nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
4 Spring Annotation Support
4,1 Introduction to 32EE Annotation
Annotation is the code about the code that is metadata about the program itself. 1n
other words information about the code is provided at the source code. Annotations are
parsed/processed by compilers, annotation-processing tools and also executed at
runtime.
Annotations have been introduced in DK 1.5. It allows the programmers to specify the
information about the code at the source code level itself. There are several ways we
can use annotations. Few helps in understanding the source code (like documentation
assistance) @override is the annotation that will be used when we override a method
from base class. This annotation doesn’t have any impact on run-time behavior, rather
it helps javadoc complier to generate documentation based on it.
Apart from these annotations we Have another way in"using annotations-which assist
source code generators to generate source codevusing them. If we take example as
Web Services, in order to expose a class as web service, we need to mark the class as
@WebService. This annotation would be read by a tool and generates class to expose
that class as web service.
Along with this there is another way, where when you mark a class with annotation,
the run-time engine will executes the class based on that annotation with which it
marked. For example, when you mark a class with @EJB, the class would be exposed
as Enterprise Java Bean by the container rather than @ simple pojo.
By the above we can understand that using annotations, a programmer can specify the
various behavioral aspects of your code like documentation, code generation and run-
time behavior. This helps in RAPIO application development where in instead of
specifying the information about your code in xml configuration file, the sare can be
specified by marking your classes with annotations.
Note: - Always your annotation configuration will be overwritten with the xml
configuration if provided.
4.2 Spring Annotation Support
‘Spring support to annotations is an incremental development effort. Spring 2.0 has a
very little support to annotation, when it comes ta spring 2.5; it has extended its
framework to support various aspects of spring development using annotations. In
spring 3.0 it started supporting java config project annotations as well.
113 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.%
‘Nagar, Cell. 9246212143. Phone: 040-64512786
4
|
iMr. Sriman ‘Spring Framework
The journey to spring annotations has been started in spring 2.0; it has added
@Configuration, @Repository and @Required annotations. Along with this it added
support to declarative and annotation based aspect} AOP.
In spring 2.5 it has added few more annotations @Autowired, @Qualifier and @Scope.
In addition in introduced stereotype annotations @Component, @Controller and
@Service.
In spring 3.0 few more annotations has been added like @Lazy, @Bean, @DependsOn
etc, In addition to spring based metadata annotation support, it has started adoption
ISR - 250 Java Config project annotations like @PostConstruct, @PreDestory,
@Resource, @Inject and @Named etc.
The below table list spring supported and Java Config project supported annotations.
@Configuration No Support
@Required
@Repository
+ @Autowired No Support
+ @Qualifier
+ @Scope
‘Stereotyped annotations
“|* @Component
+ @Service
+ Controller
+ @Bean + @PostConstruct
+ @Dependson + @PreDestroy
+ @Lazy + @Resource
+ @Value + @inject
@Named
Let’s explore these annotations with examples.
4.2.1 Working with @Configuration and @Bean
Instead of declaring a class as spring bean in a configuration file, you can declare it in
a class as well. The class in which you want to provide the configuration about other
beans, that class is called configuration class and you need to annotate with
@Configuration. In this class you need to provide methods which are responsible for
creating objects of your bean classes, these methods has to be annotated with @Bean.
Now while creating the core container, instead of using XMLBeanFactory, you need to
créaté it Using AnnotationConfigApplicationContext by passing the configuration class
as input.
114 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman ‘Spring Framework
AppConfig.java
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
>
y
MyService.java
public class MyService {
public void doSomestuff() {
// some dummy logic
d
ConfigurationTest.java
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
MyService myService = ctx,getBean(MyService.class);
myService.doSomeStuff();
4.2.2 Working with @Required
In spring 1.x onwards we have dependency check. For a bean if you want to detect
unresolved dependencies of a bean, you can use dependency check. In this IOC
container will check whether all the bean dependencies, which is expressed in its
properties are satisfied or not. The problem with dependency check Is you can’t impose
restriction on a certain property, either you need to check the dependencies on all
simple or object or all.
In 2.0, it has introduced an annotation @Required and dependency check has been
completely removed in 2.5. Using @Required annotation you can make, a particular
property has been set with value or not.
115 | urca SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Ceh. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
Engine java
package com.annotation.beans;
public class Engine {
private Integer id;
Private String type;
public Integer getid() {
return id;
+
@Required
Public void setId(Integer id). {
this.id = id;
+
public String getType() {
return type;
+
Public void setType(String type) {
this.type = type;
>
You can use @Required on a setter level to mark it as mandatory, Simply using
@Required annotation will not enforce the property checking, you also need to register
an RequiredAnnotationBeanPostProcessor in the configuration file as shown below.
application-context.xml
<1 - -if you don’t provide value for id, raises error - ->
“T1"/>
(
(or)
type" value="T1"/>
Spring Framework
In order to detect @Autowire either you need to use or
need to declare a bean whose class is.
org.springframework.beans.factory.annotation AutowiredAnnotationBeanPostProcessor.
4.2.4 Working with @Qualifier
If you have more than one beans of type Engine in the configuration, as @Autowire will
perform injection byType, it will not be able to make the decision of which bean has to
be injected and will raise ambiguity error, To resolve this we need to perform byName,
this can be done with @Qualifier as shown below.
Using Qualifier
(ignored few sections for clarity)
public class Motor {
private Engine engine;
@Autowired(required=false)
@Qualifier("engine2”)
public void setEngine(Engine engine) {
this.engine = engine;
+
119 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212143. Phoné: 040-64512786Mr. Sriman Spring Framework
application-context.xml
"22"/>
"T1"/>
Only the bean whose qualifier value is “engine2" will be injected into Motor class
engine attribute, so indirectly using @Qualifier we are able to perform byName
injection.
4.2.5 Working with stereotype annotations @Component, @Repository,
@Service and @Controfler
In addition to @Repository annotation in spring 2.0, spring 2.5 has added stereotype
annotations @Component, @Service and @Controller to make your classes as spring
beans.
When you mark you class with any of the above annotations those classes will be
exposed as spring beans by the container. Based on the type of class you are trying to
expose you need to use appropriate annotations.
@Component - This acts as a more generic stereotype annotation to manage any
‘component by spring, whereas the other annotations are specialized for the specific
use cases.
@Repository - This is used for exposing a DAO class as a spring bean. Even though
database specific semantics are not imposed by using it, it helps you in applying
exception translations on these @Repository classes using AOP.
@Service - The service layer class are annotated with @Service, even though the
current release of the spring doesn’t has any impact on using it (other than exposing
that class as spring bean), but future releases of spring might add some specializations
on those classes.
@Controller - When you mark a class with @Controller, it will be exposed as spring
MVC controller to handle form submissions.
120 | OURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
‘Nagar, Cell. 9246212143, Phone: 040-64512786Mr. Sriman. Spring Framework
Ina spring core/spring jdbc applications you can use @Component, @Service or
@Repository whereas @Controller can be used only in a Spring MVC application.
‘The below examples shows how to use @Component, but you can mark that class with
@Service or @Repository as well, where the end effect would be same.
Motor.java
(ignored few sections for clarity)
@Component(“motor”)
public class Motor {
private Engine engine;
@Autowired(required=false)
public void setEngine(Engine engine) {
this.engine = engine;
+
>
With the above configuration, the class will be exposed as spring bean with id “motor”.
In order to detect the @Component or stereotype annotations you need to use the tag
as shown
below.
application-context.xml
You can retrieve the bean with context.getBean("motor”),
4.3 Spring Java Config annotations
As explained earlier from spring 3.x it has added support to Java Config annotal
‘support, this means when you mark you classes with any of the above discussed
annotations like @Component or @Autowired, you classes will be tightly coupled with
spring framework and will lose invasive feature of spring.
in
In order to retain loosely coupled feature, it spring has added support to java
annotations, so when we use these annotations in spring applications, those will be
‘ead by spring container and add spring specific behavior to your classes. If you use in
J2EE enviroriment, those will behave based on container specification.
121 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R.
Nagar, Cell. 9246212143, Phoné: 040-64512786
a ee
sli emt sii i in hn tecaahetMr, Sriman. Spring Framework
4.3.1 Working with @Inject
@inject is a j2ee specific annotation, used for injecting/autowiring one class into
another. This is more similar to @Autowired spring annotation. But the difference
between them is @Autowire supports required attribute where @Inject doesn't has it.
@inject also injects a bean into another bean byType as similar to @Autowired. The
advantage of @Inject is it is from java (Javax.inject package) which means even you
separate your application from spring, still your classes can work with java rather than
bounded to spring.
Motor.java
(ignored few sections for clarity)
@Component(“motor”)
public class Motor {
Private Engine engine;
@lnject
Public void setEngine(Engine engine) {
this.engine = engine;
+
+
Along with this you need to use to
detect it by core container.
4.3.2 Working with @Named
There are two usages of @Named annotation
1) When you try to inject a bean using @Inject annotation it will performs injection
byType, if you have more than one beans of that type in the application, the
container will throw ambiguity error. In order to resolve it you need to use @Named
annotation.
122 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R.
Nagar, Cell. 9246212143, Phone: 040-64512786Mr, Sriman Spring Framework
application-context.xmt
“id” value="22"/>
type" value="T1"/>
rayengine"/>
124 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
‘Nagar, Cell. 9246212143, Phone: 040-64512786Mr, Sriman. Spring Framework
4.3.4 Working with @PostConstruct and @PreDestroy
As we discussed, Bean Lifecycle you can perform Initialization an a bean after injecting
the dependent objects using init-method declaration or InitializingBean interface
afterPropertiesSet and Destruction on a bean while removing a bean from core
container using destroy-method or DisposableBean interface destroy() method.
Along with the above twa ways, you can mark any arbitrary method on a class with
@PostContruct and @PreDestory annotations. When you mark a method with
@PostConstruct annotation, this method will be invoked by core container after
injecting the dependent objects into the bean. When you mark a method with
@PreDestory annotation, this method will be invoked as part of bean destruction
process,
So, the @PostContruct and @PreDestory or annotation based \ifecycle methods.
Motor.java
@Named(“motor")
public dlass Motor {
private Engine engine;
@PostConstruct
Public void Init() {
// (will be invoked after performing injection
@Resource
Public void setEngine(Engine engine) {
this.engine = engine;
>
@PreDestory
public void releaset) {
// Cwill be invoked while Iam removing from container
+
125 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R.
‘Nagar, Cell. 9246212143. Phone: 040-64512786
|Mr. Sriman Spring Framework
5 Aspect Oriented Programming (AOP)
AOP stands for Aspect Oriented Programming; it is a programming model or paradigm
that allows you to apply cross-cutting logic across various components of your
application in a decoupled manner.
How we have Object oriented programming, similarly AOP Is also a programming
paradigm, which defines some set of principles. If you write a program following the
AOP principles then it is called AOP style of programming.
In every program there will be two types of logic, one is called primary business logic
and other one is helper logic which makes your primary business logic work better. For
‘example calculating the loan amount will be primary business fogic, but in addition we
may write some logging, here logging is called secondary logic because without logging
our functionality will be fulfilled but without loan calculation logic we cannot say our
application is complete.
Now logging will be written in one place of the application or will be written across
several, as logging wili be done across various components of the application so it is
called cross-cutting logic.
Generalized examples of cross-cutting concerns are Auditing, Security, Logging,
Transactions, Profiling and Caching etc.
Ina traditional OOPS application if you want to apply a piece of code across various
classés, you need to copy paste the code or wrap the code in a method and call at
Various places. The problem with this approach is your primary business logic is mixed
with the cross-cutting logic and at any point of time if you want to remove your cross-
cutting concern; you need to modify the source code. So, in order to overcome this,
AOP helps you in separating the business logic from cross-cutting concerns.
By the above, we can understand that AOP compliments OOP but never AOP replaces
OOP. The key unit of modularity in OOP is class, whereas in AOP it is Aspect. As how
we have various principles of OOP like abstraction, encapsulation etc., AOP also has
principles describing the nature of its use. Following are the AOP principles.
5.1 AOP Pi les
1) Aspect - Aspect is the piece of code that has to be applied across various classes
of the application
2) JoinPoint - The point at which you want to apply the aspect logic, generally in
‘spring you can apply an aspect at method execution.
3) Advice ~ Action taken by an aspect at a particular JoinPoint. Advice indicates
how you want to apply the aspect on a joinpoint. There are multiple types of
advices like before advice, after returning advice, around advice and throws
advice
4) Pointcut - Collection of joinpoint representing on wiom you want to advice the
aspect
5) Target - The class on which you want to advice the aspect.
126 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell 9246212143, Phone: 040-64512786Mr. Sriman Spring Framework
6) Weaving ~ The process of advising a target class with an aspect based on a
pointcut to build proxy
7) Proxy ~ The outcome of weaving is called proxy, where the end class generated
out of weaving process contains cross-cutting logic as well.
AOP is not something specific to spring; rather it is a programming technic similar to
OOP, so the above principles are generalized principles which can be applied to any
framework, supporting AOP programming style.
‘There are many frameworks in the market which allows you to work with AOP
programming few of them are Spring AOP, AspectJ, JAC (Java aspect components),
JBossAOP etc. AMong which the most popular once are Aspect) and Spring AOP.
Let's try to compare the features between Spring AOP and Aspect) AOP.
* Only supported joinpoint is method | « It supports various types of Joinpoints
execution like constructor execution, method
‘+ Spring supports run-time weaving; execution, field set or field get ete.
this means the proxy objects will be |» Aspect) uses compile-time weaving; this
built on fly at runtime in the Indicates your proxy classes will be
memory. available whenever you compile your.
+ Spring supports static and dynamic code.
pointcuts + Aspect] supports only static pointcuts
At the time spring released AOP, already aspect) AOP has acceptance in the market,
and seems to be more powerful than spring AOP. Spring developers instead of
comparing the strengths of each framework, they have provided integrations to
Aspect) to take the advantage of it, so spring 2. not only supports AOP it allows us to
work with Aspect] AOP as well.
In spring 2.x it provided two ways of working with Aspect) integrations, 1) Declarative
Programming model 2) Aspect Annotation model. With this we are left with three ways
‘of working with spring AOP as follows.
1) Spring AOP API (alliance API) - Programmatic approach
2) Spring Aspect declarative approach
3) Aspect) Annotation approach
Even spring has integrated with Aspect), it supports only few features of Aspect)
described as below.
1) SUill the supported Joinpoint is only a method execution.
2) Spring doesn't rely on Aspect) weaving capabilities, and uses its own weaving
module so the weaving wili happens at run-time.
3) As Aspect] doesn’t support dynamic pointeut’s, integrating with spring doesn’t
make any difference.
127 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show reem, S.R
Nagar, Cell, 9246212143, Phone: 040-64512786Mr, Sriman Spring Framework
Java Source
File
+
Aspect Weaver
Proxy Class
(a File
Diagram representing AOP Process
As described the weaving process will happen at run-time, in order to generate a class
at run-time, spring uses proxy generation libraries. Spring supports two proxy
generation libraries CGLib and JDKProxy run-time bytecode generation libraries to
generate proxy classes on fly.
5.2 Types of Advices
Spring AOP implementation supports 4 types of advices, each one js described below.
1) Around advice - This is the advice that executes the aspect around the target
class joinpoint, so here the advice method will be called before the target class
method execution. So, the advice can control the target method execution,
2) Before advice - In this always the advice method executes before the target
class method executes, Once the advice method finishes execution the control
will not returned back to the advice method.
3) After Returning advice ~ Here the advice method executes after the target class
method finishes execution, but before it returns the value to the caller.
4) Throws Advice - This advice method will be invoked only when the target class
method throws an exception.
Let us try to understand haw to work with various advices using different AOP
programming styles in the following section.
128 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, 5.R
Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
5.3 Programmatic AOP
We use Spring AOP API’s to work with programmatic AOP. As described programmatic
aop supports all the types of advices described above. Let us try to work with each
advice type in the following section.
5.3.1 Around Advice
Aspect is the cross-cutting concern which has to be applied on a target class; advice
represents the action indicating when to execute the aspect on a target class. Based on
the advice type we use, the aspect will gets attached to a target class. If it is an
around advice, the aspect will be applied before and after, which means around the
target class joinpoint execution.
If we have a usecase which demands for applying a cross-cutting concern around the
target class joinpoint, we need to use around advice, one of the example for this
caching.
Always the around advice method will be executed before your target class method
executes by passing the entire target method call information to it, In an around advice
we have three control points described below.
1) We have control over arguments; it indicates we can modify the arguments
before executing the target class method.
2) We can control the target class method execution in the advice. This means we
can even skip the target class method execution.
3) We can even modify the return value being returned by the target class method.
In order to work with any advice, first we need to have a target class, let us build the
target class first.
Math.java
package com.aa,beans;
Public class Math {
public int addvint a, int b) {
return a +b;
}
public int multiply(int a, int b) {
return a * b;
>
129 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R
Nagar, Cell. 9246212243. Phone: 040-64512786 7
\ shMr. Sriman. Spring Framework
After creating the target class, we need to code the aspect representing the advice it is
using. Create a class for example LoggingAspect which implements from
Methodinterceptor and need to override the method invoke; this method accepts a
parameter Methodinvocation, into which the entire information about the actual
method would be passed.
You can access the original parameters with which the add method was called from
Methodinterceptor by calling getArguments method on it. Along with this you can
control the method execution by calling methodinterceptor.proceed(); Up on calling the
proceed() method, the target method executes, if we don’t call proceed() method, the
target class method will never get executed, Up an finishing the target method
execution the return value being returned by target method will be given to advice
method. Here the advice can modify the return value and can return to the caller show
below.
LoggingAspect.java
package com.aa.beans;
import org.aopalliance.intercept.Methodinterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class LogaingAspect implements Methodinterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Object args[] = methodinvocation.getarguments();
String methodName = methodinvocation.getMethod().getName();
// log statement before execution
System.out.printin(“entering into method : " + methodName + *(’
+ args[0] + ",” + args[1] + ")")
J] modify arguments before calling
args[0] = (Integer) args[0] + 10;
args[1] = (Integer) args[1] + 10;
// proceed() calls the target method add
Object ret = methodInvocation.proceed();
// log statement after exection
‘System.out.printin("exiting the method
+ methodName + "(" +
args[0]
+)" + args[1] +") return value : " + ret);
J] modify return value
ret = (Integer) ret + 10;
return ret;
}
i:
130 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R.
Nagar, Cell. 9246212143. Phone: 040-64512786Mr. Sriman Spring Framework
In the above code the invoke method is executed when we call add method on the
proxy object, by passing the information about the method call to Methodinvocation
argument, Before calling the proceed) method, we are modifying the parameters, so
that with these modified values proceed will be called. Once the target method
execution finishes it returns the value as object in the proceed() method call. Here the
advice can modify the return value and can return to the called.
Once the target and advice has been built, we can perform weaving to attach the
aspect to the target. In order to perform weaving to build proxy, we need to use
ProxyFactory class. To the ProxyFactory we need to add Advice and supply the target
class on to which you want to apply that advice. The ProxyFactory will apply the advice
on that given target and generates an in-memory proxy class and instantiates and
returns that object. As we are working on Programmatic AOP, the weaving process will
be done programmatically.
AATest.java
package com.aa.test;
Import org.springframework.20p.framework,ProxyFactory;
import org.springframework.aop.support. DefaultPointcutAdvisor;
import com.aa.beans.LoggingAspect;
import com.aa.beans. LoggingDynamicPointcut
import com.aa.beans. LoggingStaticPointCut;
import com.aa.beans. Math;
public class AATest {
public static void main(String[] args)
ProxyFactory pf = new ProxyFactory();
pf.addAdvice(new LoagingAspect()));
pf.setTarget(new Math());
Math math = (Math) pf.getProxy();
System.out.printin(*Sum : * + meth.add(4, 20);
//System.out.printin("Multiplication : "+ math.multiply(1, 2));
131 | DURGA SOFTWARE SOLUTIONS, 23/3RT, Near Andhra Bank Opp: Reebok Show room, S.R.
Nagar, Cell, 9246212143. Phone: 040-64512786