Spring Cleaning How to do more with less XML

Download Spring Cleaning How to do more with less XML

Post on 06-Jan-2016

21 views

Category:

Documents

0 download

Embed Size (px)

DESCRIPTION

Spring Cleaning How to do more with less XML. Craig Walls Gateway Software Symposium 2007 craig@habuma.com Blog: http://www.springinaction.com Wiki: http://wiki.habuma.com. About you. Java? .NET? Ruby/Rails? Erlang? Java 6? Java 5? Java 1.4? Java 1.3? 1.2 or older? - PowerPoint PPT Presentation

TRANSCRIPT

  • Spring CleaningHow to do more with less XMLCraig WallsGateway Software Symposium 2007craig@habuma.comBlog: http://www.springinaction.comWiki: http://wiki.habuma.com

  • About youJava? .NET? Ruby/Rails? Erlang?Java 6? Java 5? Java 1.4? Java 1.3? 1.2 or older?Whos using Spring? How long?Spring 1.2? Spring 2? Spring 2.1?Favorite session so far?What brings you to this session?

  • About meAgile developer with SemantraNatural language business intelligenceDeveloping software professionally for over 13 yearsTelecom, Finance, Retail, EducationJava for most of thatAlso some C/C++, C#/.NET, RubySpring fanatic

  • Spring sucks!Hes not really trying to sell too many books, is he?

  • Spring sucks

    Spring is configured with XMLXML is evilEvil sucksTherefore, Spring sucks

  • The so-called solutions to XMLI dont need no stinkin dependency injection!

    Ill do it myself!

    Annotations

  • The truth about Spring and DI

    Spring != XMLSprings container is decoupled from its configuration strategy

    Spring is more than just DISpring is a full application framework

  • But Ill concede thatDI is at the core of everything you do in SpringSpring DI typically involves lots of XMLXML can be verbose

    Lets see how to do more Spring with less XML

  • Three plans of attack

    Smarter XML - Use Spring XML trickery to reduce verbosityAnnotations - Use annotations to configure SpringScripting - Use scripting to configure Spring

  • Disclaimer

    There is no one-size-fits-all fixApply an ounce of pragmatism

  • Spring XML done smartlyHoney, I shrunk the XML!

  • Smart Spring XMLShorthand XMLBean inheritenceProperty editorsThe p namespaceCustom configurationAutowiringArid POJOs (aka, extreme autowiring)

  • Shorthand XML

    Introduced in Spring 1.2

    Original and elements replaced with value and ref attributes.

  • Shorthand XML in actionPre-Spring 1.2:

    This is a string value

    Spring 1.2+:

  • Shorthand XML: Tradeoffs

    ProsMore terse

    ConsCant be used to when specifying values in collections (wellmaybe)

  • Bean inheritence

    Available in Spring since ???

    Declare common configuration details in a parent bean

    Create sub-beans that inherit from the parent

  • Bean inheritence example 1
  • Bean inheritence example 2

    Only propertiesare inherited

  • Bean inheritence tradeoffsProsHelps keep Spring configurations more DRY

    ConsA little tricky to navigate bean hierarchiesespecially without tool support

  • Property editorsSupported in all versions of SpringActually part of the JavaBeans spec

    Express complex configurations as simpler stringsProperty editors help Spring convert simple strings to complex objects

  • Springs built-in property editorsByteArrayPropertyEditorCharacterEditorCharArrayPropertyEditorClassArrayEditorClassEditorCustomBooleanEditorCustomCollectionEditorCustomDateEditorCustomMapEditorCustomNumberEditorFileEditorInputStreamEditorLocaleEditorPatternEditorPropertiesEditorResourceBundleEditorStringArrayPropertyEditorStringTrimmerEditorURIEditorURLEditor

  • Property editors in actionIn Javapublic class KnightOnCall implements Knight { ... private URL url; public void setUrl(URL url) { this.url = url; }

    private PhoneNumber phoneNumber; public void setPhoneNumber(PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; }}

    In the XML

  • Registering a customer editor

  • Spring MVC & property editorsIn Spring MVC, you might configure SimpleUrlHandlerMapping like this

    homeController loginController addSpittleController addSpitterController

    mappings isjava.util.Properties

  • Spring MVC w/property editorsBut PropertiesEditor can make it simpler

    /home.htm=homeController /login.htm=loginController /addSpittle.htm=addSpittleController /addSpitter.htm=addSpitterController

  • Allow me to digressAlthough not related to property mappings at all, Spring 2.0 introduces some handy XML-saving features

  • Property editors tradeoffsProsComplex types that normally would require lines of XML can be expressed as simple strings

    ConsNot always apparent what type is being createdLooks weird if you dont know whats going on

  • The p namespaceNew in Spring 2.0Enables very terse injection of properties as attributes of the elementMade available with

  • p example

  • p namespace tradeoffs

    ProsSuper terse

    ConsMay seem alien to developers not familiar with it

  • Custom configuration elementsAvailable since Spring 2.0Encapsulate complex bean configuration behind simpler XML elements.Spring 2.0 comes with several out-of-the-box namespacesaop, jee, lang, tx, utilMore coming in Spring 2.1:context, jmsOther Spring projects include (or will include) custom elements:Spring Security, Spring Modules, etc

  • jee namespace exampleConfigure JNDI object using :

    Using :

  • How to build custom elementCreate namespace schema (XSD)Create namespace handler classCreate element parser classCreate META-INF/spring.schemasMaps schemas to physical XSD fileCreate META-INF/spring.handlersMaps schemas to namespace handlers

  • Custom element tradeoffsProsSimplifies XML configurationEnables domain-specific configurationMore expressiveConsHides what is really being configured (that may be a good thing, though)

  • AutowiringSprings so smartlet it figure out how to wire up your bean properties

    Autowiring comes in five flavors:No - Do not autowirebyName - Inject beans into properties where the beans ID matches the propertys namebyType - Inject beans into properties where the beans type is assignable to a propertyconstructor - Choose a constructor where Spring can inject beans (by type) into the constructors argumentsautoDetect - Try constructor first, then byType

  • AutowiringAutowiring strategy can be specified on a per-bean basis or a per-XML file basis:Per bean: Set the autowire attribute on the individual elements.Available in all versions of SpringPer XML-file: Set the default-autowire attribute on the element.Available since Spring 2.0

  • Autowiring example (per bean)

  • Autowiring example (per file)

  • Autowiring tradeoffsProsCan dramatically reduce the amount of XML in a Spring configuration

    ConsAlong with terseness comes lack of clarity. What was wired where?Visualization tools (Spring IDE, BeanDoc) wont recognize autowired beans as being wired.byName autowiring couples configuration to implementation detailsbyType and constructor can be problematic when there are ambiguities

  • Arid POJOsSpring add-on by Chris Richardson (POJOs in Action)Available at http://code.google.com/p/aridpojosTurns auto-wiring up a notchAutomatically declare and autowire all beans in a specified package (or packages)Based on notion that all beans are declared similarlyAlso has an auto-DAO feature

  • Arid POJOs

    Add to Spring config with

  • Arid POJOs example 1Automatically declare all beans in a package and then autowire them byType

  • Arid POJOs tradeoffs

    All the same pros and cons as autowiringJust more so

  • Annotating SpringDependency injection is where its @

  • Annotations and Spring

    Use @AspectJ for aspectsUse @Transactional for transactionsSpring JavaConfigSpring 2.1 annotations

  • Spring without @AspectJPrior to Spring 2.0, AOP was a clumsy mess of XML:

    ...

    This is just weird

  • Spring without @AspectJSpring 2.0s aop namespace made things a little bit better

  • Spring with @AspectJSpring 2.0 also introduced integration with @AspectJNow aspects require only minimal XML

    One bean declaration for each aspect classNot true AspectJ aspectStill Spring proxyJust uses @AspectJ annotations

  • @AspectJ example

    @Aspectpublic class Minstrel { @Pointcut("execution(* *.Knight.embarkOnQuest(..))") public void embark() {}

    @AfterReturning("embark()") public void sing() { System.out.println("Fa la la!"); System.out.println("The brave knight is embarking on a quest!"); }}

  • @AspectJ exampleIn the XML

    Yepthats it.

  • @AspectJ tradeoffs

    ProsSignificantly less XML required for aspects

    ConsCouples aspect classes to AspectJNot all AspectJ pointcuts available; still proxy-based

  • @Transactional

    Prior to Spring 2.0, transactions were just as messy as other types of aspectsTransactionProxyFactoryBean instead of ProxyFactoryBeanBean inheritence helped a little

  • The tx namespaceSpring 2.0 added the tx namespaceMade things a bit simpler

  • @Transactional

    Spring 2.0 also introduced the @Transactional annotationVery appropriate use of annotationsTransactions declared with minimal XML

  • @Transactional exampleIn Java:@Transactional(propagation=Propagation.SUPPORTS)public class CustomerServiceImpl implements CustomerService { @Transactional(propagation=Propagation.REQUIRED) public void addNewCustomer(Customer customer) { ... }...}In XML:

  • @Transactional tradeoffs

    ProsLike @AspectJ, very very little XML requiredConsInvasive--Spring annotations couple your code to Spring

  • Spring JavaConfigAdd-on for Springhttp://www.springframework.org/javaconfigCurrently at version 1.0-M2aRecreates Spring XML configuration in Java using annotationsProvides several annotations f

Recommended

View more >