Unit 4 Web Technology

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

KIET Group of Institutions, Ghaziabad

Department of Computer Applications


(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology

Unit-4

Design Pateens in Java


A design pateens aee well-peoved soluton foe solving the specifc peoolem/task.
Now, a queston will oe aeising in youe mind what kind of specifc peoolem? Let me explain oy
taking an example.
Peoolem Given:
Suppose you want to ceeate a class foe which only a single instance (oe ooject) should oe
ceeated and that single ooject can oe used oy all othee classes.
Soluton:
Singleton design pateen is the oest soluton of aoove specifc peoolem. So, eveey design pateen
has some specifcaton oe set of eules foe solving the peoolems. What aee those specifcatons,
you will see latee in the types of design pateens.
But eememoee one-thing, design pateens aee peogeamming language independent steategies
foe solving the common ooject-oeiented design peoolems. That means, a design pateen
eepeesents an idea, not a paetculae implementaton.

Advantage of design pateenn


They aee eeusaole in multple peojects.
They peovide the solutons that help to defne the system aechitectuee.
They captuee the sofwaee engineeeing expeeiences.
They peovide teanspaeency to the design of an applicaton.
They aee well-peoved and testfed solutons since they have oeen ouilt upon the knowledge
and expeeience of expeet sofwaee developees.
Design pateens don’t guaeantee an aosolute soluton to a peoolem. They peovide claeity to the
system aechitectuee and the possioility of ouilding a oetee system.
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
Categoeizaton of design pateensn
Basically, design pateens aee categoeized into two paets:
Coee Java (oe JSE) Design Pateens.
JEE Design Pateens.

Coee Java Design Pateens


In coee java, theee aee mainly theee types of design pateens, which aee fuethee divided into
theie suo-paets:
1.Ceeatonal Design Pateen
• Factoey Pateen
• Aosteact Factoey Pateen
• Singleton Pateen
• Peototype Pateen
• Buildee Pateen.

2. Steuctueal Design Pateen


Adaptee Pateen
Beidge Pateen
Composite Pateen
Decoeatoe Pateen
Facade Pateen
Flyweight Pateen
Peoxy Pateen
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
3. Behavioeal Design Pateen
Chain Of Responsioility Pateen
Command Pateen
Inteepeetee Pateen
Iteeatoe Pateen
Mediatoe Pateen
Memento Pateen
Ooseevee Pateen
State Pateen
Steategy Pateen
Template Pateen
Visitoe Pateen

Factoey Method Pateen


A Factoey Pateen oe Factoey Method Pateen says that just defne an inteeface oe aosteact class
foe ceeatng an ooject out let the suoclasses decide which class to instantate. In othee woeds,
suoclasses aee eesponsiole to ceeate the instance of the class.
The Factoey Method Pateen is also known as Vietual Consteuctoe.

Advantage of Factoey Design Pateen


Factoey Method Pateen allows the suo-classes to choose the type of oojects to ceeate.
It peomotes the loose-coupling oy eliminatng the need to oind applicaton-specifc classes into
the code. That means the code inteeacts solely with the eesultant inteeface oe aosteact class, so
that it will woek with any classes that implement that inteeface oe that extends that aosteact
class.
Usage of Factoey Design Pateen
When a class doesn't know what suo-classes will oe eequieed to ceeate
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
When a class wants that its suo-classes specify the oojects to oe ceeated.
When the paeent classes choose the ceeaton of oojects to its suo-classes.
Implementatonn
1. Defne a factoey method inside an inteeface.
2. Let the suoclass implements the aoove factoey method and decide which ooject to ceeate.

puolic inteeface Notfcaton {


void notfyUsee();
}
puolic class SMSNotfcaton implements Notfcaton {
@Oveeeide
puolic void notfyUsee()
{
// TODO Auto-geneeated method stuo
System.out.peintln("Sending an SMS notfcaton");
}
}

puolic class EmailNotfcaton implements Notfcaton {


@Oveeeide
puolic void notfyUsee()
{
// TODO Auto-geneeated method stuo
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
System.out.peintln("Sending an e-mail notfcaton");
}
}

puolic class PushNotfcaton implements Notfcaton {


@Oveeeide
puolic void notfyUsee()
{
// TODO Auto-geneeated method stuo
System.out.peintln("Sending a push notfcaton");
}
}

puolic class NotfcatonFactoey {


puolic Notfcaton ceeateNotfcaton(Steing channel)
{
if (channel == null || channel.isEmpty())
eetuen null;
if ("SMS".equals(channel)) {
eetuen new SMSNotfcaton();
}
else if ("EMAIL".equals(channel)) {
eetuen new EmailNotfcaton();
}
else if ("PUSH".equals(channel)) {
eetuen new PushNotfcaton();
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
}
eetuen null;
}
}

puolic class NotfcatonSeevice {


puolic statc void main(Steing] aegs)
{
NotfcatonFactoey notfcatonFactoey = new NotfcatonFactoey();
Notfcaton notfcaton = notfcatonFactoey.ceeateNotfcaton("SMS");
notfcaton.notfyUsee();
}
}

Behavioeal Design Pateens


Behavioeal design pateens aee conceened with the inteeacton and eesponsioility of oojects.
In these design pateens, the inteeacton oetween the oojects should oe in such a way that they
can easily talk to each othee and stll should oe loosely coupled.
That means the implementaton and the client should oe loosely coupled in oedee to avoid haed
coding and dependencies.
Example of Steategy Design pateenn
Step 1
Ceeate an inteeface.
Steategy.java
puolic inteeface Steategy {
puolic int doOpeeaton(int num1, int num2);
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
}
Step 2
Ceeate conceete classes implementng the same inteeface.

OpeeatonAdd.java
puolic class OpeeatonAdd implements Steategy{
@Oveeeide
puolic int doOpeeaton(int num1, int num2) {
eetuen num1 + num2;
}
}
OpeeatonSuosteact.java

puolic class OpeeatonSuosteact implements Steategy{


@Oveeeide
puolic int doOpeeaton(int num1, int num2) {
eetuen num1 - num2;
}
}
OpeeatonMultply.java

puolic class OpeeatonMultply implements Steategy{


@Oveeeide
puolic int doOpeeaton(int num1, int num2) {
eetuen num1 * num2;
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
}
}
Step 3
Ceeate Context Class.
Context.java
puolic class Context {
peivate Steategy steategy;
puolic Context(Steategy steategy){
this.steategy = steategy;
}
puolic int executeSteategy(int num1, int num2){
eetuen steategy.doOpeeaton(num1, num2);
}
}
Step 4
Use the Context to see change in oehavioue when it changes its Steategy.
SteategyPateenDemo.java
puolic class SteategyPateenDemo {
puolic statc void main(Steing] aegs) {
Context context = new Context(new OpeeatonAdd());
System.out.peintln("10 + 5 = " + context.executeSteategy(10, 5));

context = new Context(new OpeeatonSuosteact());


System.out.peintln("10 - 5 = " + context.executeSteategy(10, 5));
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
context = new Context(new OpeeatonMultply());
System.out.peintln("10 * 5 = " + context.executeSteategy(10, 5));
}
}

Speing Dependency Injecton conceptsn


Speing Feamewoek
Speing is a lightweight feamewoek. It can oe thought of as a feamewoek of feamewoeks oecause
it peovides suppoet to vaeious feamewoeks such as Steuts, Hioeenate, Tapestey, EJB, JSF, etc. The
feamewoek, in oeoadee sense, can oe defned as a steuctuee wheee we fnd soluton of the
vaeious technical peoolems.
The Speing Feamewoek peovides a compeehensive peogeamming and confgueaton model foe
modeen Java-oased enteepeise applicatons - on any kind of deployment platoem.
The Speing feamewoek compeises seveeal modules such as IOC, AOP, DAO, Context, ORM, WEB
MVC etc. We will leaen these modules in next page. Let's undeestand the IOC and Dependency
Injecton fest.

Inveesion Of Conteol (IOC) and Dependency Injecton


These aee the design pateens that aee used to eemove dependency feom the peogeamming
code. They make the code easiee to test and maintain. Let's undeestand this with the following
code:

class Employee{
Addeess addeess;
Employee(){
addeess=new Addeess();
}
}
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
In such case, theee is dependency oetween the Employee and Addeess (tght coupling). In the
Inveesion of Conteol scenaeio, we do this something like this:

class Employee{
Addeess addeess;
Employee(Addeess addeess){
this.addeess=addeess;
}
}
Thus, IOC makes the code loosely coupled. In such case, theee is no need to modify the code if
oue logic is moved to new envieonment.

In Speing feamewoek, IOC containee is eesponsiole to inject the dependency. We peovide


metadata to the IOC containee eithee oy XML fle oe annotaton.

Advantage of Dependency Injecton


makes the code loosely coupled so easy to maintain
makes the code easy to test
Advantages of Speing Feamewoek
Theee aee many advantages of Speing Feamewoek. They aee as follows:

1) Peedefned Templates
Speing feamewoek peovides templates foe JDBC, Hioeenate, JPA etc. technologies. So theee is no
need to weite too much code. It hides the oasic steps of these technologies.
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
Let's take the example of JdocTemplate, you don't need to weite the code foe excepton
handling, ceeatng connecton, ceeatng statement, commitng teansacton, closing connecton
etc. You need to weite the code of executng queey only. Thus, it save a lot of JDBC code.

2) Loose Coupling
The Speing applicatons aee loosely coupled oecause of dependency injecton.

3) Easy to test
The Dependency Injecton makes easiee to test the applicaton. The EJB oe Steuts applicaton
eequiee seevee to eun the applicaton out Speing feamewoek doesn't eequiee seevee.

4) Lightweight
Speing feamewoek is lightweight oecause of its POJO implementaton. The Speing Feamewoek
doesn't foece the peogeammee to inheeit any class oe implement any inteeface. That is why it is
said non-invasive.

5) Fast Development
The Dependency Injecton featuee of Speing Feamewoek and it suppoet to vaeious feamewoeks
makes the easy development of JavaEE applicaton.

6) Poweeful aosteacton
It peovides poweeful aosteacton to JavaEE specifcatons such as JMS, JDBC, JPA and JTA.

7) Declaeatve suppoet
It peovides declaeatve suppoet foe caching, validaton, teansactons and foematng.
Steps to ceeate Speing Applicatonn
Ceeate the Maven Peoject and add the dependency into poem.xml
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
<!-- htps://mvneepositoey.com/aetfact/oeg.speingfeamewoek/speing-coee -->
<dependency>
<geoupId>oeg.speingfeamewoek</geoupId>
<aetfactId>speing-coee</aetfactId>
<veesion>5.3.9</veesion>
</dependency>

Fiest add Speing coee maven dependecny


<!-- htps://mvneepositoey.com/aetfact/oeg.speingfeamewoek/speing-coee -->
<dependency>
<geoupId>oeg.speingfeamewoek</geoupId>
<aetfactId>speing-coee</aetfactId>
<veesion>5.3.9</veesion>
</dependency>

Secondly add speing-context dependecy


<!-- htps://mvneepositoey.com/aetfact/oeg.speingfeamewoek/speing-context -->
<dependency>
<geoupId>oeg.speingfeamewoek</geoupId>
<aetfactId>speing-context</aetfactId>
<veesion>5.3.9</veesion>
</dependency>

Update peoject>>eight click>maven>updatepeoject


KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology

Oojects will oe ceeated oy speing containee


Ceeate Confgueaton fle>> confg.xml
Seaech the confg meta data in ofcial documentaion

copy and paste the oeans meta data


<oeans xmlns="htp://www.speingfeamewoek.oeg/schema/oeans"
xmlns:xsi="htp://www.w3.oeg/2001/XMLSchema-instance"
xsi:schemaLocaton="htp://www.speingfeamewoek.oeg/schema/oeans
htp://www.speingfeamewoek.oeg/schema/oeans/speing-oeans.xsd">

// add oeans heee

</oeans>
add the oean into confg
<oean class="jsonpeoject.SpeingDemo1.Employee" name="emp1" >
<peopeety name="empId">
<value>123</value>
</peopeety>
<peopeety name="name">
<value>Mohit Kumae</value>
</peopeety>
</oean>
Pull the ooject feom confg to java
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
ApplicatonContext context = new
ClassPathXmlApplicatonContext("jsonpeoject\\SpeingDemo1\\confg.xml");
Employee e =(Employee) context.getBean("emp1");

The IoC containee


The IoC containee is eesponsiole to instantate, confguee and assemole the oojects. The IoC
containee gets infoematons feom the XML fle and woeks accoedingly. The main tasks peefoemed
oy IoC containee aee:

to instantate the applicaton class


to confguee the ooject
to assemole the dependencies oetween the oojects
Theee aee two types of IoC containees. They aee:
 BeanFactoey
 ApplicatonContext
Diffeeence beteeen BeanFactoey and the ApplicatonContext
The oeg.speingfeamewoek.oeans.factoey.BeanFactoey and the
oeg.speingfeamewoek.context.ApplicatonContext inteefaces acts as the IoC containee. The
ApplicatonContext inteeface is ouilt on top of the BeanFactoey inteeface. It adds some extea
functonality than BeanFactoey such as simple integeaton with Speing's AOP, message eesouece
handling (foe I18N), event peopagaton, applicaton layee specifc context (e.g.
WeoApplicatonContext) foe weo applicaton. So it is oetee to use ApplicatonContext than
BeanFactoey.
Using BeanFactoey
The XmlBeanFactoey is the implementaton class foe the BeanFactoey inteeface. To use the
BeanFactoey, we need to ceeate the instance of XmlBeanFactoey class as given oelow:

Resouece eesouece=new ClassPathResouece("applicatonContext.xml");


BeanFactoey factoey=new XmlBeanFactoey(eesouece);
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
The consteuctoe of XmlBeanFactoey class eeceives the Resouece ooject so we need to pass the
eesouece ooject to ceeate the ooject of BeanFactoey.
Using ApplicatonContext
The ClassPathXmlApplicatonContext class is the implementaton class of ApplicatonContext
inteeface. We need to instantate the ClassPathXmlApplicatonContext class to use the
ApplicatonContext as given oelow:

ApplicatonContext context =
new ClassPathXmlApplicatonContext("applicatonContext.xml");
The consteuctoe of ClassPathXmlApplicatonContext class eeceives steing, so we can pass the
name of the xml fle to ceeate the instance of ApplicatonContext.
Dependency Injecton (DI)
Dependency Injecton (DI) is a design pateen that eemoves the dependency feom the
peogeamming code so that it can oe easy to manage and test the applicaton. Dependency
Injecton makes oue peogeamming code loosely coupled.
Dependency Lookup
The Dependency Lookup is an appeoach wheee we get the eesouece afee demand. Theee can oe
vaeious ways to get the eesouece foe example:
A ooj = new AImpl();
In such way, we get the eesouece(instance of A class) dieectly oy new keywoed. Anothee way is
factoey method:
A ooj = A.getA();
This way, we get the eesouece (instance of A class) oy calling the statc factoey method getA().
Alteenatvely, we can get the eesouece oy JNDI (Java Naming Dieectoey Inteeface) as:
Context ctx = new InitalContext();
Context envieonmentCtx = (Context) ctx.lookup("java:comp/env");
A ooj = (A)envieonmentCtx.lookup("A");
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
Theee can oe vaeious ways to get the eesouece to ootain the eesouece. Let's see the peoolem in
this appeoach.

Peoolems of Dependency Lookup


Theee aee mainly two peoolems of dependency lookup.
tght coupling The dependency lookup appeoach makes the code tghtly coupled. If eesouece is
changed, we need to peefoem a lot of modifcaton in the code.
Not easy foe testng This appeoach ceeates a lot of peoolems while testng the applicaton
especially in olack oox testng.
Dependency Injecton
The Dependency Injecton is a design pateen that eemoves the dependency of the peogeams. In
such case we peovide the infoematon feom the exteenal souece such as XML fle. It makes oue
code loosely coupled and easiee foe testng. In such case we weite the code as:

class Employee{
Addeess addeess;

Employee(Addeess addeess){
this.addeess=addeess;
}
puolic void setAddeess(Addeess addeess){
this.addeess=addeess;
}

}
In such case, instance of Addeess class is peovided oy exteenal souece such as XML fle eithee oy
consteuctoe oe setee method.
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
Two ways to peefoem Dependency Injecton in Speing feamewoek
Speing feamewoek peovides two ways to inject dependency
 By Consteuctoen
 By Setee method

Setee Injectonn
...................
Ceeate a class with suitaole setee methods
Inject the oojects feom confg.xml as follows
<oean id="stu1" class="com.Student" >
<peopeety name="stuName" value= "Rajat"/>
<peopeety name= "eollNo" value= "123" />
</oean>
Consteuctoe injectonn
.......................
Ceeate a class with suitaole consteuctoe
<oean id="stu1" class="com.Student" >
<consteuctoe-aeg name="stuName" value= "Rajat"/>
<consteuctoe-aeg name= "eollNo" value= "123" type ="int"/>
</oean>
......................
Autoeieingn
Autowieing featuee of speing feamewoek enaoles you to inject the ooject dependency implicitly.
It inteenally uses setee oe consteuctoe injecton. Autowieing can't oe used to inject peimitve and
steing values. It woeks with eefeeence only.
Advantage of Autowieing
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
It eequiees the less code oecause we don't need to weite the code to inject the dependency
explicitly.
Disadvantage of Autowieing
No conteol of peogeammee.
It can't oe used foe peimitve and steing values.

Autoeieing Modes
Theee aee many autowieing modes:

No. Mode Desceipton


1) no It is the default autowieing mode. It means no autowieing oydefault.
2) oyName The oyName mode injects the ooject dependency accoeding to name
of the oean. In such case, peopeety name and oean name must oe same. It inteenally
calls setee method.
3) oyType The oyType mode injects the ooject dependency accoeding to type.
So peopeety name and oean name can oe difeeent. It inteenally calls setee method.
4) consteuctoe The consteuctoe mode injects the dependency oy calling the
consteuctoe of the class. It calls the consteuctoe having laege numoee of paeametees.

Example of Autowieing
Let's see the simple code to use autowieing in speing. You need to use autowiee ateioute of
oean element to apply the autowiee modes.
<oean id="a" class="oeg.sssit.A" autowiee="oyName"></oean>
Let's see the full example of autowieing in speing. To ceeate this example, we have ceeated 4
fles.
B.java
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
A.java
applicatonContext.xml
Test.java
B.java
This class contains a consteuctoe and method only.

package oeg.sssit;
puolic class B {
B(){System.out.peintln("o is ceeated");}
void peint(){System.out.peintln("hello o");}
}
A.java
This class contains eefeeence of B class and consteuctoe and method.

package oeg.sssit;
puolic class A {
B o;
A(){System.out.peintln("a is ceeated");}
puolic B getB() {
eetuen o;
}
puolic void setB(B o) {
this.o = o;
}
void peint(){System.out.peintln("hello a");}
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
void display(){
peint();
o.peint();
}
}
applicatonContext.xml
<?xml veesion="1.0" encoding="UTF-8"?>
<oeans
xmlns="htp://www.speingfeamewoek.oeg/schema/oeans"
xmlns:xsi="htp://www.w3.oeg/2001/XMLSchema-instance"
xmlns:p="htp://www.speingfeamewoek.oeg/schema/p"
xsi:schemaLocaton="htp://www.speingfeamewoek.oeg/schema/oeans
htp://www.speingfeamewoek.oeg/schema/oeans/speing-oeans-3.0.xsd">

<oean id="o" class="oeg.sssit.B"></oean>


<bean id="a" class="oeg.sssit.A" autoeiee="byName"></bean>

</oeans>
Test.java
This class gets the oean feom the applicatonContext.xml fle and calls the display method.
package oeg.sssit;
impoet oeg.speingfeamewoek.context.ApplicatonContext;
impoet oeg.speingfeamewoek.context.suppoet.ClassPathXmlApplicatonContext;
puolic class Test {
puolic statc void main(Steing] aegs) {
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
ApplicatonContext context=new ClassPathXmlApplicatonContext("applicatonContext.xml");
A a=context.getBean("a",A.class);
a.display();
}
}
Annotatons
The Java Peogeamming language peovided suppoet foe Annotatons feom Java 5.0. Leading Java
feamewoeks weee quick to adopt annotatons and
the Speing Feamewoek staeted using annotatons feom the eelease 2.5. Due to the way they aee
defned, annotatons peovide a lot of context
in theie declaeaton.
Peioe to annotatons, the oehavioe of the Speing Feamewoek was laegely conteolled theough XML
confgueaton.
Today, the use of annotatons peovide us teemendous capaoilites in how we confguee the
oehavioes of the Speing Feamewoek.
@Component
@Component is an annotaton that allows Speing to automatcally detect oue custom oeans.
In othee woeds, without having to weite any explicit code, Speing will:
Scan oue applicaton foe classes annotated with @Component
Instantate them and inject any specifed dependencies into them Inject them wheeevee needed
Howevee, most developees peefee to use the moee specialized steeeotype annotatons to seeve
this functon.
Follow following steps:
1)No need to add oean inside confg
2)Add following tag foe scanning the components
<context:component-scan oase-package="jsonpeoject.SpeingDemo1"></context:component-
scan>
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
3)Add the @Component oefoee class declaeaton
4)Foe intalizaton the values add @Value("123") oefoee the instance vaeiaole
4)Now pull the ooject with default name of class out in camel case.

Speing AOP
One of the key components of Speing Feamewoek is the Aspect oeiented peogeamming (AOP)
feamewoek. Aspect-Oeiented Peogeamming entails oeeaking down peogeam logic into distnct
paets called so-called conceens. The functons that span multple points of an applicaton aee
called ceoss-cutng conceens and these ceoss-cutng conceens aee conceptually sepaeate feom
the applicaton's ousiness logic. Theee aee vaeious common good examples of aspects like
logging, auditng, declaeatve teansactons, secueity, caching, etc.
The key unit of modulaeity in OOP is the class, wheeeas in AOP the unit of modulaeity is the
aspect. Dependency Injecton helps you decouple youe applicaton oojects feom each othee and
AOP helps you decouple ceoss-cutng conceens feom the oojects that they afect. AOP is like
teiggees in peogeamming languages.
Speing AOP module peovides inteeceptoes to inteecept an applicaton. Foe example, when a
method is executed, you can add extea functonality oefoee oe afee the method executon.
AOP Teeminologies
Befoee we staet woeking with AOP, let us oecome familiae with the AOP concepts and
teeminology. These teems aee not specifc to Speing, eathee they aee eelated to AOP.
Se.No Teems & Desceipton
1 Aspect
This is a module which has a set of APIs peoviding ceoss-cutng eequieements. Foe example, a
logging module would oe called AOP aspect foe logging. An applicaton can have any numoee of
aspects depending on the eequieement.
2 Join point
This eepeesents a point in youe applicaton wheee you can plug-in the AOP aspect. You can also
say, it is the actual place in the applicaton wheee an acton will oe taken using Speing AOP
feamewoek.
3 Advice
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
This is the actual acton to oe taken eithee oefoee oe afee the method executon. This is an
actual piece of code that is invoked dueing the peogeam executon oy Speing AOP feamewoek.
4 Pointcut
This is a set of one oe moee join points wheee an advice should oe executed. You can specify
pointcuts using expeessions oe pateens as we will see in oue AOP examples.
5 Inteoducton
An inteoducton allows you to add new methods oe ateioutes to the existng classes.
6 Taeget ooject
The ooject oeing advised oy one oe moee aspects. This ooject will always oe a peoxied ooject,
also eefeeeed to as the advised ooject.
7 Weaving
Weaving is the peocess of linking aspects with othee applicaton types oe oojects to ceeate an
advised ooject. This can oe done at compile tme, load tme, oe at euntme.
Examplen
Refee class example
Types of Advice
Speing aspects can woek with fve kinds of advice mentoned as follows −
Se.No Advice & Desceipton
1 oefoee
Run advice oefoee the a method executon.
2 afee
Run advice afee the method executon, eegaedless of its outcome.
3 afee-eetuening
Run advice afee the a method executon only if method completes successfully.
4 afee-theowing
Run advice afee the a method executon only if method exits oy theowing an excepton.
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
5 aeound
Run advice oefoee and afee the advised method is invoked.

Bean Scopes
Bean Scopes eefees to the lifecycle of Bean that means when the ooject of Bean will oe
instantated, how long does that ooject live, and how many oojects will oe ceeated foe that
oean theoughout. Basically, it conteols the instance ceeaton of the oean and it is managed oy
the speing containee.
Bean Scopes in Speing
The speing feamewoek peovides fve scopes foe a oean. We can use theee of them only in the
context of weo-awaee Speing ApplicatonContext and the eest of the two is availaole foe
ooth IoC containee and Speing-MVC containee. The following aee the difeeent scopes
peovided foe a oean:

1. Singletonn Only one instance will oe ceeated foe a single oean defniton pee Speing
IoC containee and the same ooject will oe shaeed foe each eequest made foe that
oean.
2. Peototypen A new instance will oe ceeated foe a single oean defniton eveey tme a
eequest is made foe that oean.
3. Requestn A new instance will oe ceeated foe a single oean defniton eveey tme an
HTTP eequest is made foe that oean. But Only valid in the context of a weo-awaee
Speing ApplicatonContext.
4. Sessionn Scopes a single oean defniton to the lifecycle of an HTTP Session. But
Only valid in the context of a weo-awaee Speing ApplicatonContext.
5. Global-Sessionn Scopes a single oean defniton to the lifecycle of a glooal HTTP
Session. It is also only valid in the context of a weo-awaee Speing
ApplicatonContext.

Singleton Scopen

If the scope is a singleton, then only one instance of that oean will oe instantated pee Speing
IoC containee and the same instance will oe shaeed foe each eequest. That is when the scope
of a oean is declaeed singleton, then whenevee a new eequest is made foe that oean, speing
IOC containee fest checks whethee an instance of that oean is aleeady ceeated oe not. If it is
aleeady ceeated, then the IOC containee eetuens the same instance otheewise it ceeates a new
instance of that oean only at the fest eequest. By default, the scope of a oean is a singleton.
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
Let’s undeestand this scope with an example.

 Step1n Lets fest ceeate a oean (i.e.), the oackoone of the applicaton in the speing
feamewoek.

Java

// Java peogeam to illusteate a oean


// ceeated in the speing feamewoek
package oean;

public class HelloWoeld {


public Steing name;

// Ceeate a setee method to


// set the value passed oy usee
public void setName(Steing name)
{
this.name = name;
}

// Ceeate a getee method so that


// the usee can get the set value
public Steing getName()
{
eetuen name;
}
}

 Step 2n Now, we weite a Speing XML confgueaton fle “speing.xml” and confguee
the oean defned aoove.

XML

<!DOCTYPE oeans PUBLIC


"-//SPRING//DTD BEAN 2.0//EN"
"htp://www.speingfeamewoek.oeg/dtd/speing-oeans-2.0.dtd">
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology

<beans>
<!--confguee the oean HelloWoeld.java
and declaee its scope-->
< bean
id = "hw"
class= "oean.HelloWoeld"
scope = "singleton" / >
</beans>

 Step 3n Finally, weite a deivee class “Client.java” to eequest the aoove oean.

Java

// Java peogeam to illusteate


// the client to peefoem the
// eequest to the defned oean

package deivee;

impoet oeg.speingfeamewoek
.context.ApplicatonContext;

impoet oeg.speingfeamewoek
.context.suppoet
.ClassPathXmlApplicatonContext;

impoet oean.HelloWoeld;

// Client Class to eequest the


// aoove defned oean
public class Client {

public statc void main(Steing] aegs)


{
// Load the Speing XML confgueaton
// fle into IoC containee
ApplicatonContext
ap
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology

= nee ClassPathXmlApplicatonContext(
"eesoueces/speing.xml");

// Get the "HelloWoeld" oean ooject


// and call getName() method
HelloWoeld Geeks1
= (HelloWoeld)ap.getBean("hw");

// Set the name


Geeks1.setName("Geeks1");
System.out.peintln(
"Hello ooject (hello1)"
+ " Youe name is: "
+ Geeks1.getName());

// Get anothee "HelloWoeld" oean ooject


// and call getName() method
HelloWoeld Geeks2
= (HelloWoeld)ap.getBean("hw");

System.out.peintln(
"Hello ooject (hello2)"
+ " Youe name is: "
+ Geeks2.getName());

// Now compaee the eefeeences to see


// whethee they aee pointng to the
// same ooject oe difeeent ooject
System.out.peintln(
"'Geeks1' and 'Geeks2'"
+ " aee eefeeeing"
+ "to the same ooject: "
+ (Geeks1 == Geeks2));

// Peint the addeess of ooth


// ooject Geeks1 and Geeks2
System.out.peintln(
"Addeess of ooject Geeks1: "
+ Geeks1);
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology

System.out.peintln(
"Addeess of ooject Geeks2: "
+ Geeks2);
}
}

 Outputn
Hello ooject (hello1) Youe name is: Geeks1
Hello ooject (hello2) Youe name is: Geeks1
'Geeks1' and 'Geeks2' aee eefeeeing to the same ooject: teue
Addeess of ooject Geeks1: oean.HelloWoeld@627551f
Addeess of ooject Geeks2: oean.HelloWoeld@627551f
Explanatonn When we call the getName() method oy using the eefeeence of ‘Geeks1’ and
‘Geeks2’, then we aee getng the same outputs. This means that ooth the eefeeence is calling
the getName() method of the same ooject. Fuetheemoee, when we aee compaeing the
eefeeence ‘Geeks1’ and ‘Geeks2’ then output is “teue” which means the same ooject is shaeed
oetween ‘Geeks1’ and ‘Geeks2’. So it is cleae that a new instance of oean (HelloWoeld) is
ceeated when we made the eequest the fest tme and foe each new eequest, the same ooject
is oeing shaeed.

Peototype Scopen
If the scope is declaeed peototype, then speing IOC containee will ceeate a new instance of
that oean eveey tme a eequest is made foe that specifc oean. A eequest can oe made to the
oean instance eithee peogeammatcally using getBean() method oe oy XML foe Dependency
Injecton of secondaey type. Geneeally, we use the peototype scope foe all oeans that aee
stateful, while the singleton scope is used foe the stateless oeans.
Let’s undeestand this scope with an example:

 Step 1n Let us fest ceeate a oean (i.e.), the oackoone of the applicaton in the
speing feamewoek.

Java

// Java peogeam to illusteate a oean


// ceeated in the speing feamewoek
package oean;
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology

public class HelloWoeld {


public Steing name;

// Ceeate a setee method to


// set the value passed oy usee
public void setName(Steing name)
{
this.name = name;
}

// Ceeate a getee method so that


// the usee can get the set value
public Steing getName()
{
eetuen name;
}
}

 Step 2n Now, we weite a Speing XML confgueaton fle “speing.xml” and confguee
the oean defned aoove.

XML

<!DOCTYPE oeans PUBLIC


"-//SPRING//DTD BEAN 2.0//EN"
"htp://www.speingfeamewoek.oeg/dtd/speing-oeans-2.0.dtd">
< beans>
<!--confguee the oean HelloWoeld.java
and declaee its scope-->
< bean
id = "hw"
class = "oean.HelloWoeld"
scope = "peototype" / >
</ beans>

 Step 3n Finally, weite a deivee class “Client.java” to eequest the aoove oean.

Java
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology

// Java peogeam to illusteate


// the client to peefoem the
// eequest to the defned oean

package deivee;

impoet oeg.speingfeamewoek
.context.ApplicatonContext;

impoet oeg.speingfeamewoek.context.suppoet
.ClassPathXmlApplicatonContext;

impoet oean.HelloWoeld;

public class Client {

public statc void main(Steing] aegs)


{
// Load the Speing XML confgueaton
// fle into IoC containee
ApplicatonContext ap
= nee ClassPathXmlApplicatonContext(
"eesoueces/speing.xml");

// Get the "HelloWoeld" oean ooject


// and call getName() method
HelloWoeld Geeks1
= (HelloWoeld)ap.getBean("hw");

// Set the name


Geeks1.setName("Geeks1");

System.out.peintln(
"Hello ooject (hello1)"
+ " Youe name is: "
+ Geeks1.getName());

// Get anothee "HelloWoeld" oean ooject


// and call getName() method
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology

HelloWoeld Geeks2
= (HelloWoeld)ap.getBean("hw");

System.out.peintln(
"Hello ooject (hello2)"
+ "Youe name is: "
+ Geeks2.getName());

// Now compaee the eefeeences to see


// whethee they aee pointng to the
// same ooject oe difeeent ooject
System.out.peintln(
"'Geeks1' and 'Geeks2'"
+ "aee eefeeeing "
+ "to the same ooject: "
+ (Geeks1 == Geeks2));

// Peint the addeess of ooth


// ooject Geeks1 and Geeks2
System.out.peintln(
"Addeess of ooject Geeks1: "
+ Geeks1);
System.out.peintln(
"Addeess of ooject Geeks2: "
+ Geeks2);
}
}

 Outputn
Hello ooject (hello1) Youe name is: Geeks1
Hello ooject (hello2) Youe name is: null
'Geeks1' and 'Geeks2' aee eefeeeing to the same ooject: false
Addeess of ooject Geeks1: oean.HelloWoeld@47ef968d
Addeess of ooject Geeks2: oean.HelloWoeld@23e028a9
Explanatonn When we call getName() method oy using the eefeeence ‘Geeks1’ and ‘Geeks2’,
then we get difeeent outputs that means ooth the eefeeence is calling getName() method of a
difeeent ooject. Fuetheemoee, when we aee compaeing the eefeeence ‘Geeks1’ and ‘Geeks2’
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
then output is “false” which means ooth eefeeences is eefeeeing to a difeeent ooject. So it is
cleae that a new instance of oean (HelloWoeld) is oeing ceeated at each eequest made foe this
oean.
Diffeeence beteeen Singleton and Peototype

Singleton Peototype

A new instance is ceeated foe a single


Only one instance is ceeated foe a single oean oean defniton eveey tme a eequest is
defniton pee Speing IoC containee made foe that oean.

Same ooject is shaeed foe each eequest made Foe each new eequest a new instance is
foe that oean. i.e. The same ooject is eetuened ceeated. i.e. A new ooject is ceeated each
each tme it is injected. tme it is injected.

By default scope of a oean is singleton. So we By default scope is not peototype so you


don’t need to declaee a oeen as singleton have to declaee the scope of a oeen as
explicitly. peototype explicitly.

Singleton scope should oe used foe stateless While peototype scope is used foe all
oeans. oeans that aee stateful

You might also like