Spring Intro

You might also like

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

Welcome

Overview of the Spring Framework

Ernest Hill ernesthill@earthlink.net

Why the Spring Framework

Design Techniques and Coding Standards for J2EE Projects &ntroducing the Spring(ra$e"ork

http !!""".theser#erside.co$!articles!content!%o dJohnson&nter#ie"!JohnsonChapter'.pdf http !!""".theser#erside.co$!resources!article.js p)l*Spring(ra$e"ork

What is the Spring Framework?

+ open source project "hose $ain goals are to

,- .ake J2EE easier to use /0 pro#iding a la0ered architecture that is internall0 consistent 2- Pro$ote good progra$$ing practices.

How does it achieve it's goal?

10 pro#iding a set of $odules that can /e used in concert or indi#iduall0

Spring Overview

Full-Fledged Spring Web pplication !sage

"iddle #ier

#ransparent $emote ccess

%&' bstraction (ayer

Spring )ore

Designed for "orking "ith Ja#a1eans 2ia 1ean(actor0

'ean Factory

3ight "eight container 3oads 1ean Definitions Ena/les o/ject to /e retrie#ed /0 na$e &nstantiates one or $ore instance of a /ean .anages relationships /et"een o/jects

'ean *efinition

Defines the /ean class The /ean identifiers To singleton or not Properties and colla/orators Constructor argu$ents &nitiali4ation $ethod Destruction $ethod

+nversion of )ontrol, *ependency +n-ection


1eans do not do a lookup to resol#e depen5 dencies The container injects the dependenc0 T"o $ajor #ariants
Setter5/ased dependenc0 injection Constructor5/ased dependenc0 injection

Setter-based dependency in-ection


Container calls setters on the /ean after in#oking an argu$entless constructor 1eans /ased on setter5/ased dependenc0 are true Ja#a1eans 6se of setter5/ased dependenc0 is ad#ocated /0 Spring

%.ample of Setter 'ased +n-ection


<bean id=exampleBean class=examples.ExampleBean> <property name=beanOne><ref bean=anotherBean/></property> <propetry name=beanTwo><ref bean=someBean /></propery> <property name="integerProperty">1</property> </bean> <bean id=anotherBean class=examples.AnotherBean /> <bean id=someBean class=examples.someBean />

public class ExampleBean { pri#ate +nother1ean /ean7ne8 pri#ate so$e1ean /eanT"o8 pri#ate int i8 pu/lic #oid set1ean7ne9+nother1ean /ean7ne- : this./ean7ne * /ean7ne8 ; pu/lic #oid set1eanT"o9So$e1ean /eanT"o - : this./eanT"o * /eanT"o8 ; ; pu/lic #oid set&ntegerPropert09int i - : this.i * i8 ;

)onstructor-based *ependency +n-ection


%eali4ed /0 in#oking a constructor "ith a nu$/er of argu$ents .a0 /e prefered as $eans of insuring that /eans can not /e constructed in an in#alid state

%.ample of )onstructor 'ased +n-ection


<bean id=exampleBean class=examples.ExampleBean> <constructor-arg><ref bean=anotherBean/></constructor-arg> <constructor-arg><ref bean=someBean/></constructor-arg> <constructor-arg>1</constructor-arg> </bean> <bean id=anotherBean class=examples.AnotherBean /> <bean id=someBean class =examples.SomeBean/>

Public class ExampleBean { private AnotherBean beanOne; private SomeBean beanTwo; private int i; public ExampleBean ( AnotherBean anotherBean, SomeBean someBean, int i ) { this.beanOne = anotherBean; this.beanTwo = someBean; this.i = i; } }

dvantages of *ependency +n-ection


Co$ponents are si$pler to "rite Co$ponents are easier to test 7/jects do not depend on the container +P& 7/jects can run outside the container

%.ample of 'eanFactory !sage


InputStream inputStream = new FileInputStream(beans.xml); BeanFactory factory = new XMLBeanFactory(inputStream); // Check if a bean definition exists by the name exampleBean if ( factory.containsBean(exampleBean) { // exampleBean definition exists } // Can throw NoSuchBeanDefinition ExampleBean eb = (ExampleBean) factory.getBean(exampleBean); // Can throw BeanNotOfRequiredTypeException ExampleBean eb = (ExampleBean) factory.getBean(exampleBean, ExampleBean.class ); // Can throw NoSuchBeanDefinition if ( factory.isSingleton(exampleBean ) { // this bean is a singleton } String[] aliasas = factory.getAliases(exampleBean);

/roperty %ditors

Con#enient to represent a propert0 in a hu5 $an reada/le for$ and con#ert it /ack to o/ject Propert0 Editors $ust i$ple$ent ja5 #a./eans.Propert0Editor

'uilt-in /roperty %ditors

Standard Ja#a Propert0 Editors Standard Spring Custo$ Spring

1ool< 10te< Color< Dou/le< (loat< (ont< &nt< 3ong< Short< String Class< (ile< 3ocal< Properties< String+rra0< 6%3 Custo$1oolean< Custo$Date< Custo$=u$/er< StringTri$$er

pplication )onte.t

1ean(actor0 functionalit0 in a $ore fra$e5 "ork5st0le can /e created declarati#el0 using for e>5 a$ple a Conte>t3oader

dded functionality of the pplication)onte.t


.essageSource< pro#iding access to $es5 sages in< i,?n5st0le +ccess to resources< like 6%3s and files E#ent propagation to /eans i$ple$enting the +pplication3istener interface 3oading of $ultiple conte>ts< allo"ing so$e of the$ to /e focused and used for e>a$ple onl0 /0 the "e/5la0er of an application

!sing the "essageSource


+pplicationConte>t interface e>tends an in5 terface called .essageSource @hen an +pplicationConte>t gets loaded< it auto$aticall0 searches for a .essage5 Source /ean defined in the conte>t na$ed $essageSource &f it canAt find an0 source for $essages< an e$pt0 Static.essageSource "ill /e instan5 tiated

"essage Source +nterface


String get.essage 9String code< 7/jectBC args< String default< 3ocale locString get.essage 9String code< 7/jectBC args< 3ocale locString get.essage9.essageSource%esol#5 a/le resol#a/le< 3ocale locale-

"essage Source +mplementations


%esource1undle.essageSource %eloada/le1undle.essageSource Static.essageSource +ll i$ple$ent Hierachical.essageSource

$esource'undle"essageSource %.ample
<beans> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageS ource"> <property name="basenames"> <list> <value>format</value> <value>exceptions</value> <value>windows</value> </list> </property> </bean> </beans>

/ropagating %vents

Pro#ided #ia the +pplicationE#ent class and +pplication3istener interface Standard 7/ser#er Pattern

'uilt-in %vents

Conte>t%efreshedE#ent Conte>tClosedE#ent %equestHandledE#ent

)onte.t$efreshed%vent

E#ent pu/lished "hen the +pplicationCon5 te>t is initiali4ed or refreshed. &nitiali4ed here $eans that all /eans are loaded< sin5 gletons are pre5instantiated and the +pplica5 tionConte>t is read0 for use

)onte.t)losed%vent

E#ent pu/lished "hen the +pplicationCon5 te>t is closed< using the close9- $ethod on the +pplicationConte>t. Closed here $eans that singletons are destro0ed

$e0uestHandled%vent

+ "e/5specific e#ent telling all /eans that a HTTP request has /een ser#iced 9i.e. this "ill /e pu/lished after the request has /een finished-. =ote that this e#ent is onl0 appli5 ca/le for "e/ applications using SpringAs DispatcherSer#let

)ustom %vents

+ll 0ou need to do is call the pu/lishE#ent9$ethod on the +pplicationConte>t

)ustom %vent %.ample pplication )onte.t


<bean id="emailer" class="example.EmailBean"> <property name="blackList"> <list> <value>black@list.org</value> <value>white@list.org</value> <value>john@doe.org</value> </list> </property> </bean> <bean id="blackListListener" class="example.BlackListNotifier"> <property name="notificationAddress"> <value>spam@list.org</value> </property> </bean>

)ustom %vent %.ample ctual 'eans


public class EmailBean implements ApplicationContextAware { private List blackList; public void setBlackList(List blackList) { this.blackList = blackList; } public void setApplicationContext(ApplicationContext ctx) {this.ctx = ctx;} public void sendEmail(String address, String text) { if (blackList.contains(address)) { BlackListEvent evt = new BlackListEvent(address, text); ctx.publishEvent(evt); return; } } } public class BlackListNotifier implement ApplicationListener { private String notificationAddress; public void setNotificationAddress(String notificationAddress) { this.notificationAddress = notificationAddress; } public void onApplicationEvent(ApplicationEvent evt) { if (evt instanceof BlackListEvent) {// notify appropriate person } }

!sing $esources Within Spring


+pplicationConte>t i$ple$ents %e5 source3oader interface %esource get%esource9 String location(ull0 qualified 6%3s< Dfile C !test.dataE %elati#e (ile Paths< D@E15&=(!test.dataE Classpath psuedo 6%3 Dclasspath test.dataE

e>ists9- 5 Checks if the resource e>ists< re5 turning false if it doesnAt get&nputStrea$9- 5 7pens an &nputStrea$ on the resource and returns it &s7pen9- 5 %eturn "hether this resource represents a handle "ith an open strea$. &f true< the &nputStrea$ cannot /e read $ulti5 ple ti$es< and $ust /e read and closed to a#oid resource leaks. FetDescription9- 5 %eturns a description of the resource< often the full0 qualified file na$e or the actual 6%3 Fet(ile9- 5 %eturn a (ile handle for this re5 source

$esource +nterface

%.tra marker interface

pu/lic interface +pplicationConte>t+"are


#oid set+pplicationConte>t9+pplicationConte>t conte>t-

)reating an pplication)onte.t from a web application


Can /e created declarati#el0 using for e>5 a$ple a Conte>t3oader Can also /e created progra$$aticall0

)onte.t(oader +mplementations

Conte>t3oader3istener Conte>t3oaderSer#let
Ser#let 2.2 Co$pati/le

Ser#let 2.' and possi/le 2.G co$pati/le

)onte.t(oader(istener %.ample
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/daoContext.xml /WEBINF/applicationContext.xml</param-value> </context-param> <listener> <listenerclass>org.springframework.web.context.ContextLoaderListener</list ener-class> </listener>

)onte.t(oaderServlet %.ample
<servlet> <servlet-name>context</servlet-name> <servletclass>org.springframework.web.context.ContextLoaderServlet</se rvlet-class> <load-on-startup>1</load-on-startup> </servlet>

Spring O/

+7P deco$poses progra$s into aspects

O/ )oncepts

+spect Joinpoint +d#ice PointCut &ntroduction Target 7/ject +7P pro>0 @ea#ing

spect

The $odulari4ation a concern that $ight other"ise cut across $ultiple o/jects. Transaction $anage$ent is a good e>a$5 ple Spring i$ple$ents +spects as +d#isors and &nterceptors

&oin/oint

+ point during the e>ecution a the progra$< such a "hen a $ethod is in#oked or an e>5 ception is thro"n

dvice

The action that is to /e taken at a particular jointpoint. T0pes of ad#ise include


+round 1efore Thro"s +fter %eturning

Sprint $aints a chain of AinterceptorsA around the joinpoint

/ointcut

+ set of joinpoints specif0ing "hen an ad5 #ice should e>ecute

+ntroduction

+dding $ethods of fields to an ad#ised class Spring allo"s 0ou to introduce ne" inter5 faces to ad#ised o/jects

#arget

7/ject containing the joinpoint +lso referred to as the ad#ised or pro>ied o/ject

O/ /ro.y

The o/ject created /0 the +7P fra$e"ork that includes the ad#ise. Spring "ill create a pro>0 using a JDH d05 na$ic pro>0 or a CF3&1 pro>0.

Weaving

+sse$/ling the aspects to create an ad5 #ised o/ject. Can /e done at co$pile ti$e like +spectJ. Spring perfor$s "ea#ing at runti$e

Spring O/ )apabilities

&$ple$ented in pure Ja#a Suita/le for use in J2EE container since does not need to control the class loader hi5 erach0 Spring supports interception of $ethods Does not support field interception Pro#ides classes to represent pointcuts and different ad#ise t0pes Spring ad#ises o/ject at instance< rather than class loader le#el

Spring * O

+i$ed at $aking it eas0 to "ork "ith data access technologies like JD1C< Hi/ernate or JD7 +llo"s 0ou to s"itch /et"een the$ fairl0 easil0

)onsistent %.ception Hierarchy

Pro#ides an +P& that $o#es tedious error handling out of the application into the fra$e"ork @raps e>ceptions con#erting the$ fro$ proprietar0 checked e>ceptions to a/stract5 ed runti$e e>ceptions E>a$ines $etadata to ascertain the data/ase uses this kno"ledge to $ap e>5 ception to correct e>ception in hierarch0

)onsistent bstract )lasses for * O Support


Jd/cDaoSupport

%equires a datasource to /e set %equires a Session(actor0 to /e set %equires a Persistence.anager to /e set

Hi/ernateDaoSupport JdoSDaoSupport

Spring Web "1)


Po"erful and highl0 configura/le Designed around a DispatcherSer#let 6nlike Struts "hich forces 0our +ction and (or$ o/ject into concrete inheritance< Spring .2C is entirel0 /ased on interfaces 2ie" agnostic< 0ou donAt get pushed into JSP SpringControllers are configured #ia De5 pendenc0 &njection

Features of Spring Web "1)

Clear separation of roles controller #s #al5 idator #s co$$and o/ject #s for$ o/ject #s $odel o/ject Straightfor"ard configuration of /oth fra$5 "ork and application classes as Ja#a1eans =on5intrusi#e< use "hate#er Controller 0ou need 9 plain< co$$and< for$< "i4ard< $ulti5 action or custo$- instead of +ction!+ction(or$ for e#er0thing

Features of Spring Web "1)

%esua/le /usiness code< no need for dupli5 cation. 6se e>isting /usiness o/jects as co$$ands or for$ o/jects instead of $irror5 ing the$ in special +ction(or$ classes. Handler and #ie" $apping strategies fro$ si$ple to sophisticated instead of one "a0 %elated Projects %ich Client Platfor$
Sprint %CP

2alidation

Co$$ons5#alidator +ttri/ute /ased

$esources

The Spring "e/ site

http !!""".springfra$e"ork.org http !!""".theser#erside.co$!articles!article.tss)l *Spring(ra$e"ork

&ntroducing the Spring (ra$e"ork

E>pert one5on5one J2EE Design and De#el5 op$ent

10 %od Johnson Chapter ' for a#aila/le at http !!""".theser#erside.co$!articles!content!%odJohn

$esources

E>pert 7ne5on5one J2EE De#elop$ent "ithout EJ1


10 %od Johnson and Jrgen Hller

De#eloping a Spring (ra$e"ork .2C appli5 cation step5/05step &ntroduction to the Spring (ra$e"ork
10 Eduardo &sso &to

http !!""".springfra$e"ork.org!docs!.2C5step5/05step!Spring5.2C5step5/05step.h

http !!""".springfra$e"ork.org!do"nloads!Eduardo&ssao!Spr

You might also like