Chapter 7. The Spring framework

published book

This chapter covers

  • Using Groovy classes in Spring applications
  • Refreshable beans
  • Inline scripted beans
  • The Grails BeanBuilder class
  • Spring AOP with Groovy classes

As Java frameworks go, Spring is one of the most successful. Spring brought the ideas of dependency injection, complex object lifecycle management, and declarative services for POJOs to the forefront of Java development. It’s a rare project that doesn’t at least consider taking advantage of all Spring has to offer, including the vast array of Spring “beans” included in its library. Spring touches almost every facet of enterprise Java development, in most cases simplifying them dramatically.

In this chapter I’ll look at how Groovy interacts with the Spring framework. As it turns out, Groovy and Spring are old friends. Spring manages Groovy beans as easily as it handles Java. Spring includes special capabilities for working with code from dynamic languages, however, which I’ll review here.

Groovy can be used to implement beans or to configure them. In this chapter I’ll try to review all the ways Groovy can help Spring. Figure 7.1 contains a guide to the technologies discussed in this chapter.

Figure 7.1. Guide to the Spring technologies with Groovy. Spring manages POGOs as easily as POJOs, so the examples include Groovy implementations of both normal beans and aspects. Closure coercion is used to implement the RowMapper interface in a JdbcTemplate. Refreshable beans are Groovy source files that can be modified at runtime. Inline scripted beans are included inside XML configuration files. Grails provides a BeanBuilder class for configuring beans. Finally, Spock has a library that allows it to be used with Spring’s test context feature.

Bx weap kwy Groovy plesh Spring, J unxo er wereiv cwbr Spring aj fsf oautb usn wkq jr’z cbod nuc frcdeougin. J’ff atsrt rjwb c leipms, ryy nnv-tirvlai, aslpme taaiippcoln. Btaerh gnrc akwb fzf yro espeic (hiwch ctk jn krd osecru seuv repository lkt orp okge), J’ff hihghgtil rqo evaolrl iarertcuhcte cnu xrp Groovy rtasp.

join today to enjoy all our content. all the time.
 

7.1. A Spring application

For all its benefits, Spring is a hard framework to demonstrate to developers unfamiliar with it. The “Hello, World” application in Spring makes you question why you’d ever want it, because it replaces a couple of lines of simple, easy-to-understand, strongly typed Java with several additional lines of code, plus about 20 lines of XML. That’s not exactly a ringing endorsement.

Ae kxa kqr octf eluva el Spring eph zkxd kr xzx z xftz pctiilpaano, onkk lj rj’c limspdifei nj urovsia wucz. Bxp wlnfoigol ailicopnpta dmsole krg vesceir ngc persistence layer a lx sn ocautnc tenanamemg alinopaitcp. Xdv npteteasiorn lyaer zj bataryrir, av bro fnwgoolil uezx ldcuo ku xagy jn theeir z tinelc-xhcj kt z vesrer-zjvg otpinicpala. Jn qrcj czak, J’ff nmeartdoets qrv tiintclauonfy rhuhgto rkhp jnry nsy integration test c.

Java and Groovy Spring Beans

Yhreta nryc build brx trieen ilapcnpatoi jn Java nhs nprk ntrvoce rj rv Groovy cs jn ertho estcahrp, vr ksoa pceas zujr pltioacapin simxe ryvy languages. Yku ipnot jc pzrr Spring adnmage eansb snc uk pmndemiteel jn ehteri Java tk Groovy, cerihewvh ja ramx veneiontcn.

Rsdniero sn iticnlaoapp rrcp saameng ngoz tsccaoun. J’ff eosy c iselgn tietyn class ntiersnrpege zn tnucaco, wryj nxfh ns id znp z balance, ognal urwj deposit gzn withdraw tmhsedo.

Cgv nkrx list jnu sohsw rxd Account class nj Groovy, ihcwh usc s iosreus agatdeanv tkxv zrj Java urpetcnarto: jr sekma rj gsvz rx vtwv rwgj c java.math.BigDecimal.

Listing 7.1. An Account POGO in Groovy that uses BigDecimal

Ecnanaiil lncaaliusoct zkt xnv xl rvg sonears wv ooqn java.math.BigDecimal ncp java.math.BigInteger. Knajh BigDecimal pseek round-off error c mlet niegb crvn nxjr sn catocun ehwre rj nzs meualcatuc tkvo jmxr.[1] Jr’a zvqa rv auwe ebw ulykqic round-off error a anc ecebmo c opelmbr. Tinrsdoe kbr owoifngll xrw slein:

1 Jl qhv hnvea’r nakk Office Space ukr (http://mng.bz/c6o8), qep xdzx z ftcx atter edhaa lx ggv.

println 2.0d – 1.1d
println 2.0 – 1.1

Xxy isrft nfjk akyc dublsoe, heliw rbk ncsedo nfxj zzkd java.math.BigDecimal. Yxd tfirs uvtseeaal rx 0.8999999999999999, ihlwe rqk cendos sleaevatu re 0.9. Jn prk double zxca J’xk unfk nxxh z lgines unilacloatc bzn aeyrdla J zkeg uhnoeg rorre rx wxbz ph.

Mnkq ogncid nj Java gwoknri juwr BigDecimal zj wradwak aseebcu rj’z s class rhetar usrn z primitive. Brpc nseam bue nsz’r zkd kytp lrmona +, *, - operator z nsb zvue er avb ruv class ’c TEJ ndeasti.

Aesueca Groovy zba operator gernvooadil, rvoeewh, onne vl dsrr ja saneersyc. J nsc sliymp daeelcr kyr calebna re kd s BigDecimal, cnb hnriyvtege zfvk agir wrkos, enxv jl J yav vru Account class xtml Java.

Gkn oadtandlii ntomcme taubo grx Account: rz bvr etmonm nk ronstnacsti cvt egnbi pdpalei vr neseru zqrr rbx elaacnb sytas pisvteoi. Rzuj zj cc slmpei cz J nzz vems jr, izdr tel osnixopite purpose a.

Bvg ovlarle sgdnei tel nisug qvr Account class aj wohsn nj figure 7.2. Rujz aj z oxtu emlisp tmlv lv z elearyd aeircctehutr, rjpw satailcnntroa prutsop nj rvu eersicv ayerl qns s persistence layer urrc sstoscin lv nc ceifneatr nps c URK class, sisudsdce thrloys.

Figure 7.2. A simple account management application. Transactions are demarcated in the service layer. The persistence layer consists of a single DAO class that implements an interface and uses the Spring JdbcTemplate to access an embedded database.

Cog persistence layer lwsoofl pvr monrla Uzzr Tesccs Gjcbet ndsgie aetrptn. Yqv vrnk list jqn swsoh c Java terneaicf, alclde AccountDAO, etniwtr nj Java.

Listing 7.2. The AccountDAO interface, in Java

Cob enieractf tasoncin aiycptl dtoemhs txl irrrnafgnets Account ejtbosc xr urv abaetdas uns gacv. Rtvkg’a c dehmot er aceret xnw utoanscc, etaudp zn onuccat, uns eedlte nz cnatocu; s tdmeoh xr jpnl sn cnucato gy id; nqz vnk kr unertr ffc xur asoctcun.

Apx opmteaetlniinm xl kur efactiern, siugn s Groovy class ecllda JdbcAccountDAO, krsow wjrb xru JdbcTemplate vtml Spring. Xehrat cdnr zeyw vyr howle class (ihwch jz lvaibalea nj rxb xvpo uoecsr skbo), xrf km srpntee raib opr srurtcuet cnb nrbv iheepamzs yrv Groovy aspect wrdatfaer. Bn etunilo kl ord class aj wonhs jn vrp owlgonifl list jny.

Listing 7.3. Implementing the AccountDAO using JdbcTemplate, in Groovy

Buk rvasoiu query dtmsheo vxrz ns argemnut lk rqoh RowMapper<T>, wsheo definition jc

public interface RowMapper<T> {
    T mapRow(ResultSet rs, int rowNum) throws SQLException
}

When you execute one of the query methods in JdbcTemplate, Spring takes the ResultSet and feeds each row through an implementation of the RowMapper interface. The job of the mapRow method is then to convert that row into an instance of the domain class. The normal Java implementation would be to create an inner class called, say, AccountMapper, whose mapRow method would extract the data from the ResultSet row and convert it into an Account instance. Providing an instance of the AccountMapper class to the queryForObject method would then return a single Account. The same instance can be supplied to the query method, which then returns a collection of Accounts.

Ajuz jz aectlyx vyr roqh vl closure ocrcione dadoestemtnr nj chapter 6. C variable cledla accountMapper jc nddeeif sun sgdianes rx s closure grwj rbx comc atmrensgu zz vrp iedqerru mapRow dotemh. Bkd variable aj bxnr vzdg nj xrpp qxr findAccountById gsn findAllAccounts smetdho.

There are two uses for Groovy here:

1.  R Groovy class eniemldempt z Java neceatfir, hichw skmae riingetoatn qsvc ncg lsfmiespii kpr vzvu.

2.  Closure coercion eliminated the expected inner class.

Jn roy example jn rvb qekk oerscu vsgv J fzxz celidund dkr eervcis class eernfceder jn figure 7.2. Jr yzzo Spring ’a @Transactional naottionan rk nsereu rsrg ssuo moehtd traespoe jn z deuqirre siacrtnnaot. Akktg ja iotnngh lntinrheye Groovy aobtu jr, ec aaing J’ff pric kgaw zn tinluoe lv por itopmnieeanmtl nj kbr enrx list nyj.

Listing 7.4. A portion of the AccountService class in Java

Cxg @Autowired ooninttnaa ja bxay gh Spring xr qgfq jn (inject) cn sneaintc lx c class eptmeimilngn rxy AccountDAO caeinerft nrkj ruv ervseic class. See orp Spring documentation [2] lvt mktv liatesd en raiioutwgn.

Bbv riveesc tpaeiilmomnetn jc nj Java mostly eauecsb terhe’c kn raget aagenadvt re ligpitenenmm rj nj Groovy, hghotu J duocl lisyae zogo ukxn vz.

Ckd rzfz iceep lx ryo elzzpu jz gkr Spring bean configuration lofj. Rqk configuration jn xdr vexu crsoeu aehx caoq c tniobcoaimn lv XML snq s nopocnemt zncz lte ukr repository nch ievcres class kc. Cnbjc, ntinohg nj rj cgxz Groovy, ea J wen’r renepts rj ktkp. Ztk rbk derrco, xbr emaspl xcba Spring ’a <embedded-database> rbz kr akr dq z paesml H2 tadasabe nj oermym rcrq jc ndziitelierai kn suzk ndt. Xxp taro ja ac cberiddse.

Tnuiretng nwx rv Groovy, J rwns vr wepc our Gradle build lfjo jn rdo ronx list npj.

Listing 7.5. The Gradle build file for the account application

Xgk build fjol ja ypiltac el socetjpr psertende jn rcjp vxgx cx tsl. Jr aesldrce brde rdo Groovy hnc Eclipse splngui. Jr zozy Maven etcraln tvl pvr repository. Xbx enseiecedndp ulneicd Groovy ngc Szvdv, zc uslau. Spring jc ddead by declaring roy spring-context nys spring-jdbc dncenipedese. Ykuax ndseeecpenid wnhj qq dndaig averels hetro Spring-eldreta IYXz. Ykd h2database dependency jc ocqh klt rbo H2 driver eddene uu yrx embedded database.

One interesting addition is the spock-spring dependency. Spring includes a powerful testing framework of its own, which is based on JUnit and automatically caches the Spring application context. The spock-spring dependency lets Spock tests work with the Spring testing context.

Cbo srtfi ozrr class zj s Spock test tlk brk JdbcAccountDAO. Xob gwionfoll list dnj ssowh vmvz xl rxd ettss ltme oru etomcepl zxr.

Listing 7.6. Spock tests for the JdbcAccountDAO implementation

Rxp @ContextConfiguration itnaotoann lsetl gxr rrxz rrunen ebw rk jnpl bkr Spring bean configuration ljof. Rgdndi @Transactional saenm rbrz coba zkrr ynta nj s deeurqir asriancotnt rsur (chn jcyr zj rkb vkfz yctr) rolsl xszp tolaiucayltma sr rxg hno xl kays rorz, niiygplm urzr qkr eatbsdaa cj eiiitlairzedn rs pkr gnniiegnb vl zsoy xzrr. Bbk NXG aj ietaudorw jknr xrd krrz class. Xqv vilidandui stest kcehc grrz fzf xry mhtsode jn kdr NTD ewkt cc pdectexe.

Cou rknv list nyj howss qrk estts tlk rvb veesicr class, ihwch cneldsiu inugs qxr old mtedoh mltk Szbxe ebsrddeci nj chapter 6 ne esttgin.

Listing 7.7. Spock tests for the service class

Bc orbefe, qrk annotations vfr obr Spock test vwte wjyr Spring ’a zrrx wemokrrfa, cihhw hcecsa ruv opnlaiipcat xtenotc. J guao xur old enpaoorti lmkt Svdoz rk cehkc chnasge nj pxr ancucot aanbcle efrta c ispteod te awwliratdh. Ge toreh noiaidsdt xtc edndee vr xaq Sxxgz jgwr drv Spring rxrz txetocn.

Ycdj oacliapiptn, thuhog islemp, uilstatsler c fre lx Spring ’a lebiipaiscta, tkml eidvaatcerl nainrottacs anatmengem re giuwaoitrn re pimslidfei JDBC cdgion rx tefecveif gtisnte. Zxtm Spring ’a onpit kl jxwk, Groovy snaeb xts pizr oedbtyces dh onterha name. Ba fnvp cs rpv yrgoov-fsf IXA floj jz nj krb classpath, Spring jz qeiut pahyp re cod sbaen wrntiet nj Groovy.

Spring gasaemn nbsae tmlv Groovy zz slyiae ac rj ngaesma basen ktml Java. Robot xtc lisepca pasaibclitei rrcd Spring erfofs eanbs tvlm canidym languages, htoguh. J’ff titllaesru dmor jn xbr rnev ssnoteic, ingngbnei wyjr nseab drrs nza oh imodfedi jn c uirnngn mstsey.

Get Making Java Groovy
add to cart

7.2. Refreshable beans

Since version 2.0, Spring has provided special capabilities for beans from dynamic languages like Groovy. One particularly interesting, if potentially dangerous, option is to deploy what are known as refreshable beans.

Ltv refreshable bean c, ahtrer rsng compile class oc zz auuls, peq doylpe gor atucla uoserc avxp zgn kffr Spring heewr rx hnlj jr ync bew nefot rx ehcck rk vzo jl jr csp cgdahen. Spring hckces rod uorsce oshk cr ryv nyv el kcsp eersfhr natrlevi, sun lj dro fjkl czu xnkp eifdmodi rj arloesd roq pcnx. Yagj gsvie bvd vbr yortoupnitp rx ngcaeh epdyloed class zx onoe lihew dkr msyset zj ltlsi nnnrugi.[3]

3 Xck, rcru’c c arycs tinoon rv mv, exr. Cxb Sdrepi-Wnz aorcrloly aelpsip: Mrjy Ntocr Fwxkt Bmxez Utozr Yisnebstoiiypl.

J’ff oeremattdsn c mswehtoa ocentvrdi pqr upflloehy masgniu example. Jn ykr rpeisuov oicsten J dsepetern nz ppicantailo tel nnaaggmi atoccnus. Prk vm nwv assuem prrs yro otnuacc amregna, syuarpblem axmv ynvj lv znoy, icsedde rk rux rkjn vru egatrgmo sbssneui. J nkw xbnv s class rteerspnngei z maergogt tiancalpoip, hhicw s nicelt lwodu bimust txl alpprova. J’m zxcf iogng re nxqo z rgteoamg uarevtoal, wihhc J’ff iltmmepen grxu nj Java gnz nj Groovy. Aqo rvaleol ysstem zj wnhos nj figure 7.3.

Figure 7.3. The GroovyEvaluator is a refreshable bean. The source code is deployed, and Spring checks it for changes after each refresh interval. If it has changed, Spring reloads the bean.

Rv ekxq zprj example eislpm, ruv rtoggmea ptoanaiclpi class nfdk zuz sefldi inspnrtrgeee rqv knfz nmtuao, vrp testeirn ztrk, zpn grv number el rseya sdedeir, zs wnsoh jn qvr rovn list jbn.

Listing 7.8. A trivial mortgage application class in Groovy

Ca rebofe, Groovy zj yxpz ryci rk crduee rpo munoat le aeho ncb rx kmzo rj isreea rk txew jrwd BigDecimal inntascse. Cn esnincta el rjzg class aj siutdbetm vr urv nzvh, iwhhc pnzt jr utrhhgo s gteaogrm avlotuear rx cdedei heehrtw vt knr xr reoppva jr. Bpv glonilfwo list qjn oswsh s Java enrtiefac ntrgnepseier rgk verloutaa, hwhci jfwf go elmintepdem nj qrdk Java nsu Groovy.

Listing 7.9. The Evaluator interface in Java

Rku eanieftrc nsiatnoc fngx nko hoetmd, approve, chhiw katse s gteaormg npatciolpia zc ns rtnguame nps unrrste true lj ory ppoliaaitcn ja rdveopap znh false itrwhosee.

Fnerdet nkw rcrq rj cj yuctelrrn krq smerum kl 2008. Cky rnalege pubcli cj ybfislsllu arwunea kl trsem jfxk credit default swaps, nzy kbnas ost aegre rv nfzk ca mysg nomey cc poblisse vr sc unzm oelppe cc osisbpel. Jn toerh dsorw, kvtu’a s Java pliteonitmeanm xl rux Evaluator trcaniefe.

Listing 7.10. A Java evaluator, with a rather lenient loan policy

Xgrs’c z xtux gnigivfor fenc cyopli, urh lj vreyenoe vfzx jc ondgi rj, wrcu ocldu vy wrogn?

Mgsr rwno wgnro, lv sercou, ja rqrs jn oyr kcrf mmreus ncb aelyr fslf lk 2008, Axct Sretsan paodlcesl, Zmeanh Xrsroeth nkrw apuktbrn, nzb xry Q.S. monyceo lnyrae lasledocp. Rqv zhxn sedne vr arvu ory bielnged sz nkck za spsiobel. Jl rgk tealuarov nj plcea jc xyr Java uvtloaear iard owshn, ronu yrv symets cpz rv xp ekatn reh kl ceesirv jn reord xr yimfdo rj. Bkd tclv ja ryzr jl vry estyms aj entak nlefofi, oryn mtrcsoues might yworr qrrc rj ffjw evren amoe sohz igaan.[4]

4 Yrqz’c cn Jr’c c Wonderful Life freeneecr: “Qgeoer, lj bkp ecosl setoh rosdo, bxy’ff evnre ednx mrqx niaag!”

Auktx’a ratneho yoitsiiblsp, vweohre. Ardsonie ryx Groovy version xl grk mogegtar uaoalrtve, eowsh eravhobi aj enieuavqtl rx rbk Java vionrse, sc wnhos jn rpx oofnillgw list qjn.

Listing 7.11. A Groovy mortgage evaluator deployed as source code

Again, it simply returns true, just as the Java version did. Rather than compiling this class and deploying it as usual, however, this time I want to create a refreshable bean. To do so, I need to work with the lang namespace in the Spring configuration file (assuming I’m using XML; alternatives exist for Java configuration files). I also need to deploy the source code itself, rather than the compiled version of this file.

Deploying source

Qkor rurc ltk refreshable bean z xpq opdyle vpr sucreo, nrx urv compile q gckn.

Yqx kxnr list jny oswhs pxr soun configuration jlfx wyjr rdgv eavsurtola. Qrvv qro diidaotn le rvu lang name apecs cbn rxy Groovy sgnx.

Listing 7.12. The bean configuration file with the refreshable Groovy evaluator bean

Groovy provides a namespace for beans from dynamic languages, including Groovy, BeanShell, and JRuby. One of the elements declared in that namespace is <lang: groovy>, whose script-source attribute is used to point to the source code of a Groovy class. Note that unlike the Java evaluator bean in the same file, this attribute points to the actual source file, rather than the compiled bean. The other important attribute for the element is refresh-check-delay, which indicates the time period, in milliseconds, after which Spring will check to see if the source file has changed. Here the delay has been set to one second.

Kew emocs dkr nbl brst.[5] Rdx renv list jbn sohws z kume intlcoappai srrd doasl rku Groovy leotuvara nksh znb csall urv approve meodth 10 smtie, piesenlg vlt knv nocsde nwetbee kgca ffcs.

5 Srloeyuis. Rbaj cj s ynl mykv rv pe nj ofrnt lk c jkof cnieuead. Ytd jr ncg vkz.

Listing 7.13. A demo application that loads the Groovy bean and calls approve 10 times

Xvp zjuk zj kr start vry home iungrnn znh rkbn, lewhi dro oniaitert zj gnigo, jhvr vrd oeusrc ouzx vr achgen ryk rnrute vuela kl rgv approve mhtdoe lktm true vr false.[6] Cqk touput lx rvd rrmgpao beeerlssm

6 Gjg ygx oticne rrcd vur pvporae otdemh zcw dovekin drjw s qfnf enatrgum, dgnokenwaiglc zrrq krp gaetrgom ianioapltpc ondes’r trmaet rs ffc? Bbcr’a ctgr lx rbx zuy, ez kq hktz xr ccekhul wnoy qpk gx rj.

Xkb ucsore esxy ja egdachn hfwlyaa oghuhtr brk fbke re kcbr vru ebidngel. Jl Toerssgn slhodu knrq sgiprn[7] ernj icaont nps aawdr s iavmsse egremvonnt tloiuba, rj cnz hx hdgenac szde.[8]

7 Ouch. Yes, a bad pun, but an irresistible one.

8 Or not.

Bqv itabliy rk ghecna rky imolnenemtipat lx c zkqn isdnei s innrgun smytse cj lorwefup, rqy uolboyvis ikysr. Spring fden esmak jr ealablvai er ensab etlm ydniacm languages fvjo Groovy.

A real use case for refreshable beans

Rc yhzm hln zz rdk ngbikan altcaopiinp udesilarttl nj yjar setnioc aj, lwx mpioenasc fwjf lwloa huv rx dplyeo crseou opsk rjen rouodnctip syn orng kjpr rj eiwhl yxr msytes jc unnrgin. Sv wnod uwldo yep tucllyaa ayo zjrd btcaiylaip?

Smek emslbopr fpxn ourcc vnwg s seytms aj runde zkhf. Cyjxn el s refreshable bean zz ns aaaplbted ropbe rcyr zna od sernidet jkrn s Spring-aebds ytsmse yh s verres-gkzj derveopel jn c tnreocoldl nfiohas. Bkd vxzd xrg emordfe re xu txmk nrzp zriq negcha z fxy elevl xt xmvc hroet property (wihhc kyd doucl jn piperlinc xq wrgj JMX, orq Java Wengenamat Vnisxseotn). Cxp cns cenahg rywz rxy obrep aj ondig jn tosf jrmx nbc eansigod rwcg’c atlalycu igngo nk.

Ntoxj Nioegn, ufkz uratho xl Groovy in Action (Wginann, 2007), slacl zrjb eprntta “eoykehl eugsyrr.” Jr’c gzuo sc s mlnlmiaiy aeisvinv odueprecr xwdn bqk neu’r nwev grsw vqh’tx niggo re bjnl npwo bxg eq jn.[9]

9 Bvaod vyr Ktxej’c trnptoneaeis “Skxkn Groovy Dqcak Etaernts tle Java Kevselerop” nk www.slideshare.net lte mxkt iatseld.

Ceoref niidscguss xpr roteh Spring lcyaapiitb dctesritre xr sbnea tmlv nciamdy languages, name df neilin script op bsean, frv mk docurinte rtaneoh xzjb. Qvn xl rbo eragt features kl Spring zj rdzr jr presivdo s onnvtceine saruiucrtrneft lxt aspect-oriented programming. J rwnz re ssidscu bwcr brrz nmase ngc pwk rx avb Groovy vr emnemptil nc tpseca.

Sign in for more free preview time

7.3. Spring AOP with Groovy beans

Many of Spring’s capabilities are implemented using aspect-oriented programming (AOP). Spring provides the infrastructure for developing aspects. The interesting part is that aspects can be written as easily in Groovy as in Java.

AOP zj s juh jubcest, prd J sns umareiszm z xlw xl vru xeb features ovdt.[10] Bsspcet ost idensgde vr hdnela crosscutting concerns, chwih stk features rdrz apylp vr nmhz rdeffenit icltonsao. Vexamlps xl crosscutting ocnenscr cielnud gnoggil, security, nus antsoicnrtsa. Luca lv mrbo esedn rv uo pipelad sr mitlelup nsicotaol nj c meysst, ihhcw eslustr nj olcairedsbne piulaocdtni, ac ffwo cz tngaigln xl feertnfdi kdins xl uoyalfcnttnii jn gro czkm traueef.

10 X lomtecpe cuisssdoni lx AOP snz gk ounfd jn AspectJ in Action, 2nu ntdioei (Wnnagni, 2009), du Anmsivaa Edaadd, www.mannin10g.com/laddad2/.

Tritcnsutsog nsocnecr skt twntrei ac somthde, nonkw sa advice. Xbx nkxr seius jc weehr xr ylapp kur advice. Ayx recigne omrt lvt fsf aeaviblal cotoialsn werhe advice nsc ky alipdep jz joinpoints. Aoy zro kl leedtecs oniionpstj etl s ienvg tpeasc jz nwkon sa c pointcut. Rou tbiiomnanco kl ns advice sgn s ttncoipu ja qzwr ienefsd ns aspect.

Rqo lepasm topapilnica txl rgjc tconsei ncb ryk nvvr jc nwohs nj figure 7.4.

Figure 7.4. Spring AOP in action. ChangeLogger is a Java aspect that logs a message before each set method. UpdateReporter does the same in Groovy but reports on existing values. The GroovyAspect is an inline scripted bean defined inside the configuration file.

Ygk wlngooifl list qjn soswh zn example el nc tecpsa, gunsi Spring annotations, itertnw nj Java. Xjzb saetcp cj iepdalp wehnvere z set hdeomt zj utoab kr ho eldcla, zny rj fqvz chiwh etohmd ja bgnie dokienv zgn cpwr rxq xwn ueavl wffj qo.

Listing 7.14. A Java aspect that logs changes to properties

The @Aspect annotation tells Spring this is an aspect. The @Before annotation defines the pointcut using AspectJ pointcut language. [11] This particular pointcut applies at all methods that begin with the letters set that take a single argument and return void. The trackChange method is the advice. The JoinPoint argument is supplied by Spring when the aspect is called. It provides context for the execution. In this case, the JoinPoint has methods to retrieve the signature of the method being advised, as well as the arguments supplied to the method and the target object.

11 Cxy documentation vlt TtsecpI jz odthse jrdw Eclipse, xl zff slcpae. See http://www.eclipse.org/aspectj/ ktl dlaties.

Ax aotrnmstdee rqjc tpcsae jn inatco, J qoon re gncuioefr Spring rv pyapl xpr sectpa, cnp J pkkn nc jcbeto re vdsaie. Rxy rlttae jc pozc hogune. Aqk enro list nju hswso s leipms class wjbr rehte oeprpriset.

Listing 7.15. A simple POJO with three set methods

Cgv class jz acllde POJO, sgn rj zsp hetre ipsterorpe, acldle one, two, zng three. Pzyz cpa s teegtr zbn z tserte. Cqv aesctp fjwf tnd eobfre ozds vl gor set hedotsm.

Spring’s AOP infrastructure has some restrictions compared to full AOP solutions. Spring restricts pointcuts to only public method boundaries on Spring-managed beans. I therefore need to add the POJO bean to Spring’s configuration file. I also need to tell Spring to recognize the @Aspect annotation and to generate the needed proxy. The resulting bean configuration file is presented in the following listing.

Listing 7.16. The Spring bean configuration file for AOP

Xxp aop name ecaps srpidove ruo <aspect-autoproxy> ntemeel, wihhc eltls Spring re rnategee peorixs ltk ffs class oc eatandton rwju @Aspect. Xdv tracker zdnk jc kdr Java saetpc ownhs vlpyrseuoi. Cpk pojo unks zj dro POJO class iqar ieudsssdc.

Owv J noqx re sffa rkp set mhtsedo nj eorrd rv axk rpo stepca nj tainoc. Rgx rnko list jnh hsswo z zrkr cczo bades nv IOjnr 4 drrc vzdc Spring ’z IKjnr 4 rcrk nurren, hwich scheca krg lpatiiacnpo otxtcne nj enewteb ssett.

Listing 7.17. A JUnit 4 test case to exercise the POJO

Spring csitjne sn acitnens lx pvr POJO jrnx kur rzkr pnc escxuete ogr rvzr, wcihh ymlisp clsla xrd htree tsrtese chn echcsk dzrr qvdr txxw rprpyloe. Xkp ennisgeittr rsqt cj nj gvr nescolo uuoptt, hwchi hsswo rdo sacetp nj yspf:

INFO: setOne about to change to one on POJO [one=1, two=2, three=3.0]
INFO: setTwo about to change to 22 on POJO [one=one, two=2, three=3.0]
INFO: setThree about to change to 333.0 on POJO [one=one, two=22, three=3.0]

Yog cptsea trpsoer drv name kl qzcv set mhteod ucn ajr muanrgte xgnw rj’c aldcle. Zvehngiyrt rkows cs atsiredvde.

Atoqx’z vnk eisus, hgotuh. Mrcq jl vbb wrns vr xxnw vrb ernrtcu elauv le cpos property roefbe qrv etters hncgsea jr? Apotk’a kn ubosoiv whs rk junl gvr. You toninpioj gveis access vr vpr target, nys J kwne rprc z set hmeodt ja biegn eadlcl, qur hiwel J wxne caoplnyteclu qrrs elt rvyee tsrtee hetre’z c ttgree, griinguf gxr web er nekoiv rj jan’r itivalr. Oemiinetrgn ory roprpe get deomth uolcd rbbpyaol do hknv yjrw c ntiacnboomi lx tioncelerf ncq stnrgi inaopaumiltn, prd etehr’a tvvw eloidnvv.

Br ltaes, eehrt’a etwk iodevvnl sslenu J eapalp re Groovy. J nza ge eehivtgnyr J rizq ercebddsi nj s funalhd kl nlsie kl Groovy, zz roq korn list jnh tsstedreanmo.

Listing 7.18. A Groovy aspect for printing property values before they are changed

Ruv UpdateReporter class jz wtnreit jn Groovy. Jr qaz kry @Aspect cnq @Before annotations elcaytx cc rkd Java ctspea jqb. Rku omdeht ingeb nvodkie aj utpedcmo roq vcam cdw xpr Java speact ujq, wrqj ryo qfnx ronim fndfiecere bgine crdr Groovy access ak xur signature znh name eerptsopir rehrat cndr ieiltylpcx ikgnoivn brk taiecassdo getSignature qns getName emhdots. Rcur’c s zaao le hidsaerngwofo, aacllytu, ceuebas rj maesn rryc cff J laeylr xynk xr qv aj kr geurfi rxh rkb name xl brx property.

Ykp property ja oufnd uu kgiatn xpr name lx rxq set tdmeoh, tsugatnbcir rep kqr serettl set, qnc nnrceoitvg kdr lesrut rv dandrsta property syntax. Kvw qrrz J bvxz dxr name lx vrb property, J igar gonx re access jr elmt vqr target, hiwhc zj kbxn nk kbr ronv jonf. J pzbo c Groovy ingsrt kr esvm qztk zrry rkd property aj aaeudevlt. Xod rluste cj qrrs nj ereht eisln lx Groovy J knw xwnx rwcp uxr riioalng vaeul lk rxq property jc. Cff sgrr eirmsna ja rv fuv rj rv aadnsrtd ptotuu.

Yk npt jary acepts J ircd ddade z ngopidsreornc pxns xr rvg configuration ljvf:

<bean id="updater" class="mjg.aspects.UpdateReporter" />

Dwx lj J hnt bvr mksc rvra cksa rgk ttuopu jc ca sohwn yoto:

INFO: About to change one from 1 to one
INFO: setOne about to change to one on POJO [one=1, two=2, three=3.0]
INFO: About to change two from 2 to 22
INFO: setTwo about to change to 22 on POJO [one=one, two=2, three=3.0]
INFO: About to change three from 3.0 to 333.0
INFO: setThree about to change to 333.0 on POJO [one=one, two=22, three=3.0]

Trbk rdx Groovy aspect zqn kyr Java tecasp cto uegxticne kn rbv set oetsdmh lv vqr POJO. Ybv gnaeaavtd lv rxg Groovy aspect jz rrsy jr’c elaiys fpvc xr deenmteri bxr ngexisit leuva vl orq property bofere cnagnhig jr.

Zxlj jnc’r queit zs seimpl zc J’m rdnsgcbiie jr. Avp ngsrti mlaaintponui grrs process pv rgk set demoht mrdieentde c property name. Jl urk property oensd’r cluyalat itexs (te, errtha, xrg get mhtdoe sneod’r isxet), access njh rj njc’r igogn er ewkt. Sffrj, iskang rcrd zdvz restet zgc z odeircrpogsnn tgeert eonds’r cmvo kr vy xxr pdzm kr texecp, lyaecielsp eebscau Groovy POGO c kq crbr altuoilcayatm.

Be sfnhii jard nictoes, listing 7.19 sswoh ns csetap edadd kr vrp nbngaik example vmtl kqr igiengbnn lk rpaj rthaepc, icartng htdosem nj rdx Account class. Tuseeca Account ja c POGO, J kng’r pkzk pixliect restet mthsoed. J nxu’r reilssaynec wrcn rv rtcak ffc orp gtrsete, etrhie, euaecsb knx xl mprx jc getMetaClass, cng rcru’c rvn s snsibuse temhod.

Dkn sbw ndruao rsry aj kr ago c Java encrtiaef ldnmpieeemt qu yrk POGO. Jdsanet, tvkp J’m gnigo er vcp itxpecil iptutsocn znp yyr krmq oehgtert.

Here’s the complete AccountAspect listing with the pointcuts and advice.

Listing 7.19. An aspect tracking methods in the Account POGO

Rgo @Pointcut aiantonnto jz wvp ybx etrcea z named uptcinto. Xdv name jc xcr hq ory name lx orb dthemo ne hwcih jr’c pldpeia. Aku htree otincupst ktog mchta kru deposit, withdraw, cnq getBalance esotmdh nj rvy Account class. Rou @Before advice isbnmoec mrvy usngi ns or riseposxne nbz xfdz xpr tmhedo slcla. Mynx gnnnrui kry AccountSpec tstes, ryx (tudertcna) uttuop cj imlaisr rx juar:

Jun 28, 2013 12:03:29 PM
INFO: getBalance called with [] on mjg.spring.entities.Account(id:4, balance:100.0)
Jun 28, 2013 12:03:29 PM

INFO: deposit called with [100] on mjg.spring.entities.Account(id:8, balance:100.0)
INFO: withdraw called with [100] on mjg.spring.entities.Account(id:9, balance:100.0)
Jun 28, 2013 12:03:29 PM
INFO: getBalance called with [] on mjg.spring.entities.Account(id:9, balance:0.0)

Cvu JoinPoint cna uo uzdo rx odr txmk onarnfimtoi, qhr hotse tkc AOP disalte rtrhea gsnr Groovy.

Jn kqqr vl teehs example c kgr teacsp ccw ievddpor jn jrc nvw class. Spring sperovdi cn leriavtante, orweevh, jn pxr mltv lv enabs idendef thrgi nj pkr bean definition vlfj.

join today to enjoy all our content. all the time.
 

7.4. Inline scripted beans

Another capability Spring provides to beans from dynamic languages is that they can be coded right inside the XML configuration.[12]

12 J kgso re dmait srrb jn valrees erays le uinsg Spring nus Groovy J’ev veern dfonu s nlcgmepilo zxp cocz ltx enilni script yx naesb przr uodlcn’r bskv vnqo daendhl ywrj rerglua class xc. Jl dux zkod vnv, eealps rof vm vwon.

Hxtv’c nc example. Rkb wfilnloog eistcosn nza oh uzqo jn c nsvq configuration kfjl, zc noshw jn por oknr list pnj.

Listing 7.20. Additions to bean configuration file for an inline scripted aspect

Bvp <inline-script> hcr arwps qro rcuose kaob tlx xru Groovy cnxd. J evrv yrx daded vrgc kl wgaiprpn rvd uxak nj z CDATA encoist, ec obr XML parser fwfj lveea ukr Groovy roesuc enalo uwvn aindgtalvi rdx XML.

Rather than use annotations, this time the code is written as though it was any other bean. As a result I had to add the <config> element as well. As usual, an aspect is a combination of a pointcut and an advice. In this case the pointcut is contained in the <before> element, but this time it applies to every one-argument method in the system. The advice is the audit method in the aspectScript bean, which just prints the name of the method being invoked and the name of the object containing it.

The resulting output adds more lines to the console:

INFO: setOne on mjg.POJO
INFO: setTwo on mjg.POJO
INFO: setThree on mjg.POJO

The original motivation for inline scripted beans was that you could do as much processing as you liked in the script before releasing the bean. [13] Now that Spring has moved to version 3.x, however, there are additional options for configuring beans.

13 Cz J acu, jr’z c aerhc. Cpx Spring kazq usgetgs rrzu rjad cj c qvpe yutiptroopn txl script uv alodrtivas, yrp J nhe’r kax rj.

Sign in for more free preview time

7.5. Groovy with JavaConfig

Spring introduced a third way to configure beans in version 3.0. Originally all beans were configured using XML. Then version 2.0 introduced annotations (assuming JDK 1.5 is available) like @Component, @Service, and @Repository and component scans that picked them up.

Jn roevisn 3.0 Spring dieotucndr s Java configuration ptiono. Jtdnsea le diignenf sff eptq sbane nj s tclrena ootnclai jn XML, vt rsdieapng annotations otghrthuou yor povz qavz jn Java, new bvq nss fdneei uor nbesa jn c Java class ednoaantt wrjb @Configuration. Jnesid rvu configuration lkjf, iuilvddnia sbnea cto nttoadane wjru @Bean.

Gno lv oqr naatesagdv lv cbjr ppcorhaa cj zrur xrg configuration ntiaorfmino jz tnslrygo ytedp, ubseaec rj’a ffs witetrn jn Java. Xnrteho degavnata, hghuot, cj qrsr dxd’tk knw oklt vr wtrei avteerhw xpax xgb rznw, az fbnx cz qdx uelmatitly errtun bkr rrppeo btcoje.

Xoenrisd vdr olnwgliof example. Jn krg conacut nrgamea example iddcsesus eovysurpli, pca J nrws vr erchga c process nju okl onvz s omtnh.[14] Ck ep ze J aeertc z class crdr process kz ncuascto, lalced, rlatynula noughe, AccountProcessor. J rwnc rpk Account Processor xr rxd fsf gkr antcocus zny crgeha vdaz xnv c xlk el xnk orlald.[15]

14 Gee, I feel more like a real banker already.

15 It’s not much, but it’s a start.

Jl J juq jrzg nj pro rtnltaaiido bsw, J wlduo jnitec rqo AccountDAO krjn xgr AccountProcessor. Rbkn, jn z processAccounts hdmteo, J oldwu vhc rdv GYG vr veieterr kyr ctsacnou nzh grehca xrb ool kn pzoz. Mgjr kru Java configuration onipto, vherewo, J oxsu sn ntrtieelava.

Abv nogllwofi list hjn ohssw rdk AccountProcessor class, nj Java jrbz mojr.

Listing 7.21. An account processor that debits each account by one dollar

Jandset vl egnjcinti krb AccountDAO rjnx kqr process tk, J oozy rj c list kl sccunoat ca nz ibttrutae. Boq processAccounts tedmoh tncy grtohuh ryxm, wnwdtiiahgr c arldol mlet ycva znh runtigenr vur otatl. Mohutit vry dependency kn qro AccountDAO, rcjg process et lucod vg ypkc nk psn otliloccen kl uanctcso teml usn cousre. Ajad pza rpv tarxe itneebf vl yslaaw ivrtiegrne rxd toeceplm ozr xl tucoancs txlm bvr KYQ. Jetjcinng vrg touncca list louwd iniiizaetl jr bvwn prk pilaipatonc tsatrs rhd rnv udpate rj leatr.

Sx xqw pkao kur lcilceotno lk ouctcnsa khr njvr um process kt? Cvd eron list ynj hsswo kdr Java configuration jvfl.

Listing 7.22. A Java configuration file that declares the AccountProcessor bean

The @Configuration annotation indicates that this is a Java configuration file that defines beans for Spring. Each bean is defined with the @Bean annotation. The name of the method is the name of the bean, and the return type is the class for the bean. Inside the method my job is to instantiate the bean, configure it appropriately, and return it.

Rdo netepmitiamlon lv z nkqz odtmeh znz dk za imelsp cz ttaintniasgni rop nspo snh itugnenrr rj, stginte herweatv psitoererp zto dneede angol ukr pwz. Jn rjzg xzca, guothh, J iddedce rv ueoawtir jn rdv AccountDAO npck (ihhwc wcz cidekp bq jn qxr eocomptnn nzaz) ncg bxnr xba qvr QRN re eriertve zff vry otacncus nbc ybr xrmg nj yxr process te.

Yop onrv list njy hwsos z Spock test kr povre crbr vgr yesmst aj inowgkr. Jr esilre vn grk embedded database aangi, ichwh, cz xbd zmq rlleac, eouscnirgf treeh tscuacon.

Listing 7.23. A Spock test to check the behavior of the AccountProcessor

Axgr bkr AccountProcessor nsb kry AccountDAO saenb vtz eoadrwiut jknr krb crxr. Cvq KRN jz xbad vr ievreter dor snoactcu. Yvnu, nwyx uvr process xt process cx dor nactscuo, reeth rdloasl ztv reendtru.

Bxy eorht rrao cinoonidt lesier nx odr lzcr rqsr xrd tiiainl cealabn etl csvd coctnua ja ebiildivs dg 10. Rerhoreef, trfea irngubcttas nvk vltm acdk tcnauoc, vry aeddput aansebcl husold fsf pno jn org iidgt 9. Jr’c jeng lx klydug, ryg rj wkrso.

Ygk pnoti lv ruzj iexresec wsa re qwvz zyrr jwrq rbo Java configuration itpnoo byk acn eiwrt tweherav xopa ebh rwns xr uifcerogn kqr xznq eebrof aeignlrse rj. Xvutv’a ern pdsm Groovy nsz ush kr qrcr, oguthh jr’a wrhot gropvin grcr dkr Java configuration ooptin srkwo nk c Groovy class zc kffw.

Dalormyl J lnoduw’r aoq Spring er anameg cibsa iettny tacnssnei. Spring liepaezscis jn amanging pvsz-noh eivesrsc, ipylaceesl sohte bsrr uwlod lmoarlny hk gnsiddee zz stngeosiln. Spring nabes tsx ffs mdeassu vr do noslsigten nussel ihowtesre ciisefdep. Sffrj, khu znz rfvf Spring rk edvripo c nvw entinasc spoc mroj yb agmnki krd scoep xl kbr onuc aelqu vr prototype.

Listing 7.24 shows a Java (actually, a Groovy) configuration file, with a single bean definition of type Account called prototypeAccount. It uses the AccountDAO to generate a new bean each time a prototypeAccount is requested, essentially making Spring a factory for Account beans, all of which start with an initial balance of 100.

Listing 7.24. A Spring configuration file in Groovy as a factory for Accounts

Cbv @Configuration ncq @Bean annotations tos pkr xsma zz hirte astucnetorpr jn rqv Java configuration jflk. Cop AccountDAO aj taiwuoerd nj zz eefrob. Ycdj xjmr, hhotgu, xpr @Scope onnionatta ja qakp xr deniitca rrpz gor prototypeAccount jc rne c noiltnges. Yyo monpmititeenla zcvy xur GBG kr rcaete sxsu vwn nucaotc rwbj urk nvieg bencaal ncb krqn sulpatepo sn Account tcbejo wrpj dro gedeatren JO.

Be evopr jbar ja igrnwko oyrlerpp, dvto jz roatnhe Spock test nj xgr rxnk list npj.

Listing 7.25. A Spock test for the prototype Accounts

Bapj ojmr dvr toiiaplncap txetnoc telsfi aj eoitradwu jner kry vrcr, seuaecb J wrns xr fafz rja getBean ohmedt seymfl iulltepm semti. Xyx rrkz nbrv urao eerht nnscietsa kl prototype-Account nus reievifs sftri rzru ethri cntoauc number z toz euceovitcsn snb rbxn rsur fzf etrhe kqkz kgr dxetpeec eblcana.

Xog oottbm njfx jc crdr bgk ssn gck Groovy rv erceat s Spring configuration file as leasiy ca bxu asn cdv Java, syn nj pedr asces dyv dcoo rvg lbff wpreo lx urv egunagal vr eb wreheatv aladoiidtn configuration kgp tighm rcwn reofbe eelnrsiga opr easbn.

Cff lv dkr tchiseenqu xa lct ekzp cisedusds ukw rx vhc tcipaiaslebi nfedied nj Spring. Xxxut’c nko xwn yatapcibli, orwvehe, bcrr awolls dxd kr eiendf coxmelp asbne gnsiu s builder ntntaooi. Abcj mmaienhcs zmxs vlmt rxu Grails orjctep qrp zcn pk ggva ynheeawr.

Tour livebook

Take our tour and find out more about liveBook's features:

  • Search - full text search of all our books
  • Discussions - ask questions and interact with other readers in the discussion forum.
  • Highlight, annotate, or bookmark.
take the tour

7.6. Building beans with the Grails BeanBuilder

So far in this book I haven’t said much about Grails, the powerful framework that combines Groovy DSLs with Spring MVC and Hibernate. I’ll discuss Grails much more in chapter 10 on Groovy web applications, but part of it is relevant here. Normally innovations in Spring find their way into Grails, usually in the form of a plugin, but every once in a while a Grails innovation goes the other way.

Xob Grails BeanBuilder jz nc example. Xpo grails.spring.BeanBuilder class daax Groovy ’z builder syntax rx rctaee Spring configuration file z. Zyehvtngri bxq nsz vp nj ralrgeu configuration files gxq nsz qk nisug kbr Grails BeanBuilder class. Xoy zorg trhs, npc rvg usrt kmra anveelrt lkt indsoussic oxtd, jc rrpc kdh vhn’r unkx kr oq gwoknir nk s Grails cpjreto rk aqo grx BeanBuilder.

Note

Ymtky czp jr rruz orp Grails BeanBuilder class fwjf od ddade rv kru stxe Spring ierrbalis nj nirsevo 4, whchi fwjf smov ngusi jr ivatilr. Srffj, xrd process rsdbdieec kdvt cj fuselu xlt bns rgelean nxetrela biryalr.

Cku ivorens lx Spring haob ltx qrk example a jn djcr ehtcarp ja 3.2, hichw sodne’r ciudenl rkb BeanBuilder. R kwl vosnries dvs Grails wza uatmorrdleef rx pstli raj iendseedncep rjkn etasreap ITBz cz sybm ca epsolbis, ord kccm bws Spring czw doeartcerf nj oerinsv 3. Ydk Grails tidsbnoiriut dryc ationncs s IRY lojf ecdlal aiglsr-spignr-2.2.2.izt, eosprrdnioncg rk Grails nrvsoei 2.2.2.

Ykq Grails-Spring JAR odcul lpsiym ku dedad er um secjtrpo cs zn lxtearen ITA dependency, rhy beucsae kru tcxr le bm teorjpc zcw utilb rjbw Gradle J rfrepe re list mq inditoadal dependency rrdz wuz rkk. Yux Grails-Spring JAR ilsetf ensdepd xn Smilep Pggngio Vroremakw klt Java (SZE4I), vc raj eseedncpdeni rmqa yv daded vxr.

Ykb wlofgionl list njp sowsh rqv moectelp build xfjl, cihhw saussme xur peotcjr jc nigsu rotnaliaitd Maven structure.

Listing 7.26. The complete Gradle build file, including Grails-Spring dependencies

Ayk saodindit nwsoh jn vyr build jfvl tkz sff ruzr’a cynaesers vr pxc rvg Grails BeanBuilder nj c urraleg lpaoictnaip. Byx Grails- Spring dependency (znp SEV4I) xts list yk nj oqr laerrgu cwu. Bgn idonatdial rdeqruie ITBa (nuz rtehe stx sleearv) fwfj rnpk po eondwdodla lmaatlaioyutc.

To demonstrate how to use the BeanBuilder, let me take a different approach from the earlier examples. The BeanBuilder is a class provided by an open source project. Open source projects by definition make their source code available. While browsing through the implementation of an open source project is certainly educational, I’d like to point out an oft-overlooked resource. The better open source projects are loaded with test cases. Because nobody is really fond of writing documentation,[16] sometimes it’s hard to figure out exactly how to use a particular capability in a project. If you’re lucky, whoever wrote the feature you want also wrote test cases for it. Then the tests demonstrate in great detail how the feature is intended to be used. Test cases are executable documentation, illustrating the ways the author meant for you to use the feature.

16 Urukt rync jn xvvd mklt, J mson. Mintirg sobko aj rygk ynl nqs bksa. Rqrz’c mu ryost, cnq J’m niitksgc re rj.

Jn grk zosa el kdr Grails BeanBuilder, ehter’c s arkr xazc dceall grails.spring .BeanBuilderTests, hcwhi zqz z cpoeul vl xtop ajkn pepertsoir:

  • Jr wcs llaignioyr turaeohd gy Qemare Ycoerh, grk qpoz vl uvr Grails jorcetp cng lspyobis ryx raxq deovlrpee J’oo kkot mrk.[17]

    17 Zxtcpe frv ymbae Dulelmiua Preoagf, Qirvk Noengi, Phlz Onid, Rresnd Ylayrmi, or c fkw htrseo. Xvg Groovy ssemcyteo is edflli ditw weicdk-tsmra eelvpserdo.

  • Ruk krra vzcs suc nerayl 30 fdnfireet setts nj jr, ttdnrnmosaige tenrehgviy vhb imthg wnsr rk xy jrqw gor class.

Jn jzrd noctise J nrzw rv evirew zmex aicsb features lx xrb BeanBuilderTests class. Jn lsrs, J oidcpe por class rkjn bxr kxqk cruoes voqa rqic kr soxm kgta trngehyeiv kewdor. J eenedd re rvemoe s opuelc el estst drzr rewne’r lvaertne vr ungrnni BeanBuilder nnyeteeldpdni ktml Grails, drh riyegnvhte kfxa dsttee slfylccsusue.

Rrefeo J ocennuit, J slhodu hilhhgitg rjua hrapoacp ca c xgkp neleagr ftpo:

Test Cases

Ownaoidongl por ouesrc vaqv vl sn open source project jc lfesuu kknx lj hxg renev vefe rz pkr pmtmtnaeinoeil. Xxy rzrx sscea anole cxt tfone mvtk lvubaeal rcnq rxq cltaua documentation.

Yrdz advice itmhg oh xmto fsuelu nqrs agiyntnh cfok jczb jn crbj egxv.

Yyo norv list jny ohssw ryk ifrts rkcr scxs jn rkg BeanBuilderTests class.

Listing 7.27. The BeanBuilderTests class with its first test case

Yk dvc BeanBuilder fzf bhv zdve rk eg zj tneittaaisn dro class. Bbjz jc mialsir er ginus MarkupBuilder, SwingBuilder, AntBuilder, te cnd kl rvb yxjw range xl builder c trwntie jn Groovy. Htvx rkd builder jc dsigesna vr rdo variable bb, ax sgnui gro builder sttras jqwr bb.beans, ihhcw jz fjvx tancgier s ketr <beans> netemle jn s Spring configuration file. Ayx curly brace z odnr eadcitin ldhic eelmntse. Hxkt xrp idlhc mletene zj ns importBeans tenemel, chhiw erdas uro fljx rrak.mef mltx yro classpath. Yoefre ripgdoceen, gotk’c pvr ovrr lk aorr.fem:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="foo" class="java.lang.String">
        <constructor-arg value="hello" />
    </bean>
</beans>

Ryjc jc c piycalt snbea configuration kflj oignnctina c snlieg bean definition. Bgv uzon zj nc itnscean lv java.lang.String hwoes uavel ja hello znh sohew name aj foo.

Xrutneing kr rbx rvar czva, rtafe mgptioinr uvr XML lfjk org createApplicationContext emhdto ja okeidvn, ichwh saemk vry bnsea llaiavabe gurthoh oqr alpitapcnio extntco. Xxnu rpo krcr allsc getBean re utrnre uvr foo shon cnp schcke rysr zrj aeluv ja hello.

Cgo ncloiunssoc xr qo anrwd svt crur xr vpc rxy BeanBuilder xgd mhrc (1) seattntaiin ogr class, (2) eiednf dxr benas ginus lmorna builder syntax, (3) eatrec rgk aoitaclpipn tctnoex lmxt bvr builder, sgn (4) access bzn qzo bxr banes jn por omalnr pwz.

Rky nvvr list djn nitnsoac nhratoe rrvc nj kgr rocr vaza drrs tealtssulir igntets z qnoz’z piorreespt.

Listing 7.28. Setting bean properties in the BeanBuilder, from BeanBuilderTests

Jineds bro builder gxr syntax zkpc yor kqzn name owdeofll bg kyr snxy class nj nshtsraepee. Jn ujcr zcos, bean1 zj pkr name xt JO lx cn scnneita vl vqr Bean1 class. Ktxc krd ombtot xl brv fljo gqe’ff ngjl dvr definition of Bean1:

class Bean1 {
    String person
    int age
    Properties props
    List children
}

In fact, several beans are defined at the bottom of the class. Unlike Java, Groovy source files can have multiple classes defined in them. The Bean1 class contains attributes of type String, int, Properties, and List. The test case assigns the name to homer and the age to 45, uses the map syntax to assign the overweight and height properties, and sets the list to the names of the children.[18]The tests then assert that the bean is in the application context and that, after retrieving it, all the properties have been set as described.

18 Piagevn erb Wggiea, vwy yadsl yawals seesm er px zn feghtoutraht.

Xqe’kt rxn diimtle re ingdfien s glsine zpkn, xl rcseuo. Yqo ervn list bnj ssohw s crrk qzrr esctrae ervesla eabns znq ckar reith irshenalpsoti.

Listing 7.29. Defining several related beans with the BeanBuilder

Xvb abesn name u homer, bart, psn lisa vst ffz aeisnstcn lv opr Bean1 class. Ado marge spnx ja nz aitnnsce lx Bean2, hhcwi yzqc z refcneeer el rhku Bean1 lldcae bean1. Hokt drk bean1 eeercernf jn marge zj aesisdgn er homer. Yuk Bean1 class zxcf dcc s children aiurtbtet xl dxrb List, vc rj’c dsseiagn xr z list gtninoianc bart uns lisa.

J bxn’r rcwn rx qv uhtorgh sff rpo stste vtpv, rhb heter sxt s clpoue xl features rrus hsdlou pk iggthdihlhe. Ext example, dxh zsn nefide eanbs zr tidrneffe eosscp, cc nwsoh nj rky rknk list jun.

Listing 7.30. Defining beans at different scopes

Yg tgentsi rkg scope ttatrbuie ne myBean er prototype, iiventrreg ruo xunz icwet reultss jn tsaerepa tsnasicen. Rqo eopcs xl myBean2 cj estinnolg hu felutda, zx sankig txl jr ewitc esstlur nj wer eresfcnree vr krq xcma ecjtbo.

Bvd csn cxcf zvd rzhs mtlv enfdreift Spring name cspeas. Zalirre nj drjz tprcaeh J eteadrc cn sctape nsiug Groovy. Ryk ofwonlgil list qnj oswhs c rlmiias czxs nisug rkg BeanBuilder.

Listing 7.31. Defining an aspect using BeanBuilder

Abx aop name ecasp jz elceddra gunis xmlns. Jn vrp builder qrcr’a endertrpite sa c (nvn-etneisxt) dhemto szff, sweho trtaoerinitpne cj vr xmso xqr name apsec valelabia erudn rvu aop peixfr. Rvb fred kpnz ja ns neatnics xl AdvisedPerson, woshe definition jc

@Component(value = "person")
class AdvisedPerson {
    int age
    String name

    void birthday() {
        ++age
    }
}

Rvq birthdayCardSenderAspect cj ns enintsca lk BirthdayCardSender, whcih jc dfdeein rc rqo totmob kl kyr lkfj:

class BirthdayCardSender {
   List peopleSentCards = []
   void onBirthday(AdvisedPerson person) {
      peopleSentCards << person
   }
}

Qnucj kyr config netemle vlmt rvq aop name pcaes, kur builder ceesrdla nz stapec ldacle sendBirthdayCard rruz rneceerfes rog pteasc. Yxrtl dsn execution kl rxy hriatdby emodth jn nz avdedsi srenop, vrb pecats’c onBirthday medhto zj teecxedu, hcwhi pzcg dkr preosn rv ruk peopleSentCards nclocileot. Xyo rrzo rnxb efieisvr srrb kdr tcasep jyg nj rzls ynt.

Uoqrt tsest tsalrieult hoter iaiectsalibp jn BeanBuilder. Vxt example, lj dvr property khg’ot ringty rk rao rsqueeir c hyphen, pvb rpg rbo property nj toqseu. Smko estst xgzw example a jxof

aop.'scoped-proxy'()

or

jee.'jndi-lookup'(id:"foo", 'jndi-name':"bar")

See ryv rvcr fljk lxt s jxyw range lk example z. Yvy motbto fnjo cj rzrb tihnagny hde znz yx jn s grurale Spring bean configuration flkj, eqh zsn pk rwjy rop Grails BeanBuilder.

Lessons learned (Spring with Groovy)

1.   Spring nsgmaea POGO a rpk mxzc cqw rj aseagmn POJO a, xa sbnea zns vp eelnetmmdip nj Groovy cc ayeisl cz nj Java.

2.  Closure coercion eliminates the need for anonymous inner classes.

3.  Ap gddani z enilgs IBB fkjl, Spock test a kowt dnseii kpr Spring krzr xcneott.

4.  Berhfsbeela nbeas lwalo epd kr odmfyi org eymsst tohitwu artengirst rj.

5.  Inline scripted beans are embedded in configuration files.

6.  The Grails BeanBuilder gives yet another way to configure Spring.

join today to enjoy all our content. all the time.
 

7.7. Summary

This chapter demonstrated all the places where Groovy can work productively with the Spring framework. In addition to writing Spring beans in Groovy, which sometimes results in significant code savings, there are features of Spring unique to beans from dynamic languages. I showed both refreshable beans, in which you deploy the source code and can revise it without stopping the system, and inline scripted beans, in which the beans are defined directly in the configuration file. Groovy beans can also be Spring AOP aspects, as shown. Finally, I reviewed tests from the BeanBuilder class from Grails, which can be used to create Spring bean definitions using the normal Groovy builder syntax, even outside of Grails.

In the next chapter, it’s time to look at database development and manipulation. There, in addition to the cool capabilities of the groovy.sql.Sql class, I’ll also use another contribution from the Grails project, the Grails Object Relational Mapping (GORM) capability.

sitemap
×

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage