Professional Documents
Culture Documents
com
tech facts at your fingertips
CONTENTS INCLUDE:
Spring Configuration
n
About Spring Configuration
n
The Beans Namespace
n
The Context Namespace
n
The AOP Namespace
n
The JEE Namespace
n
Spring Annotations By Craig Walls
n
Hot Tips and more...
Any non-trivial application is composed of two or more objects <?xml version=”1.0” encoding=”UTF-8”?>
that collaborate to perform some business logic. Traditionally, <beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
each of those objects is responsible for obtaining references
xmlns:context=”http://www.springframework.org/schema/
to those objects that it collaborates with (its dependencies). context”
This leads to tightly-coupled and hard-to-test code. xsi:schemaLocation=”http://www.springframework.org/
schema/beans
http://www.springframework.org/schema/beans/spring-
I need a
treasure map beans-2.5.xsd
I’ll give you a
treasure map http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/
Pirate spring-context-2.5.xsd”>
Spring
inj
ec
<!-- place configuration details here -->
te
di
nt
o </beans>
TreasureMap
tech facts at your fingertips
Get More Refcardz
Spring Configuration
(They’re free!)
With dependency injection, however, objects are given their
dependencies by some external entity. In other words, depen- n Authoritative content
dencies are injected into the objects that need them. In the case n Designed for developers
of a Spring-enabled application, it is the Spring container that n Written by top experts
Don’t put all your beans in one XML file. Once several XML files. Then assemble them all together when creat-
Hot your application gets beyond the trivial stage, ing the application context or by using the <import> element:
Tip you’ll likely have an impressive amount of XML <import resource=”service-layer-config.xml” />
in your Spring configuration. There’s no reason <import resource=”data-layer-config.xml” />
to put all of that configuration in a single XML file. Keep your <import resource=”transaction-config.xml” />
Spring configuration more manageable by splitting it across
<context:property-placeholder>
The AOP namespace
<context:spring-configured>
Schema URI
Context Namespace Elements www.springframework.org/schema/aop
Element Description Schema XSD
<context:annotation-config> Enables annotation-based configuration in www.springframework.org/schema/aop/spring-aop-2.5.xsd
Spring beans. This element is not needed if the
<context:component-scan> element is in use.
The aop namespace makes it possible to declare aspects,
pointcuts, and advice in a Spring context. It also provides support
<context:component-scan> Scans packages for beans to automatically register in
the Spring container. Use of this element implies the for annotation-based aspects using @AspectJ annotations.
same functionality as <context:annotation-config>. Using aspects, you can define functionality that is applied
<context:exclude-filter> Used to exclude certain classes from being (or “woven”) across many points of your application.
automatically registered by component-scan.
<context:include-filter> Used to specify which classes to include when AOP Namespace Diagram <aop:after>
component-scan automatically registers beans.
<aop:after-returning>
<aop:include>
<context:load-time-weaver> Registers an AspectJ load-time weaver.
<aop:aspectj-autoproxy> <aop:after-throwing>
<context:mbean-export> Exports beans as JMX MBeans. <beans> <aop:advisor>
<aop:config> <aop:around>
<context:mbean-server> Starts an MBean server with the Spring context. <aop:aspect>
<bean> <aop:scoped-proxy> <aop:before>
<context:property- Enables external configuration via a
placeholder> properties file. <aop:declare-parents>
As configured above, <context:component-scan> will scan the <aop:before> Declares before advice (e.g., a method to be
invoked before a pointcut executes).
“com.springinaction.service” package and will automatically
register as beans all of the classes it finds that are annotated with <aop:config> The parent element for most elements in the AOP
namespace.
@Component, @Controller, @Repository, @Service, or @Aspect.
bean when the plunder() method is executed. Likewise, the <jee:remote-slsb id=”hispaniola”
jndi-name=”ejb/PirateShip”
sayYarr() method will be invoked upon execution of the plunder() business-interface=”com.pirate.PirateShipEjb”
resource-ref=”true” />
method on any object.
<jee:jndi-lookup id=”parrot”
jndi-name=”pirate/Parrot “
resource-ref=”false” />
Reduce AOP-related XML by using @AspectJ
Hot annotations </beans>
Tip The elements in the “aop” namespace make it The first element, <jee:remote-slsb>, configures a bean named
rather easy to turn plain old Java objects into “Hispaniola” which is actually a reference to an EJB 2 remote
aspects. But the <aop:aspectj-autoproxy> stateless session bean. The EJB’s home interface is found in
element can single-handedly eliminate the JNDI under the name “java:comp/env/ejb/PirateShip”. The
need for almost all other “aop” namespace resource-ref attribute indicates that the value in jndi-name
XML. By placing <aop:aspectj-autoproxy> in should be prefixed by “java:comp/env/”. The EJB implements
your Spring configuration, you can move your methods defined in the PirateShipEjb business interface.
pointcut and advice declaration into your Java
code using @AspectJ annotations such as @ The other element, <jee:jndi-lookup>, retrieves a reference to
Aspect, @Pointcut, @Before, and @After. Refer an object from JNDI (it could be an EJB 3 session bean or just a
to Chapter 4, section 4.3.2 of Spring in Action, plain Java object). The object is found in JNDI under the name
Second Edition for more details. “pirate/Parrot”. Because resource-ref is “false”, the jndi-name
is not prefixed with “java:comp/env/”.
<jms:jca-listener-container> <lang:defaults>
<lang:bsh>
<beans> <jee:environment>
<beans> <lang:inline-script>
<jms:listener-container> <lang:groovy>
<lang:property>
<lang:jruby>
<jms:listener-container> Configures a container for standard JMS <lang:groovy> Declares a bean implemented as a Groovy script.
destination listeners.
<lang:inline-script> Embeds a scripted bean’s code directly in Spring XML.
<jms:listener> Declares a listener to a JMS destination. <lang:jruby> Declares a bean implemented as a JRuby script.
Used to create message-driven POJOs.
<lang:property> Used to inject values or references into scripted beans.
The TX namespace
Configure transactional rules in Java
Hot
Schema URI Tip If you’re looking for ways to cut back on the
www.springframework.org/schema/tx amount of XML in a Spring configuration, consider
Schema XSD using the <tx:annotation-driven> element. Once
www.springframework.org/schema/tx/spring-tx-2.5.xsd this element is in place, you can start annotating
The “tx” namespace provides support for declarative transac- your beans and their methods with @Transac-
tions across beans declared in Spring. tional to define transactional boundaries and
TX Namespace Diagram rules. Have a look at chapter 6, section 6.4.4 of
<tx:advice> <tx:attributes> <tx:method>
Spring in Action, Second Edition to learn more.
<beans>
<tx:annotation-driven>
The util namespace
TX Namespace Elements
Schema URI
Element Description
www.springframework.org/schema/util
<tx:advice> Declares transactional advice.
Schema XSD
<tx:annotation-driven> Configures Spring to use the @Transactional annotation for
transactional rules. www.springframework.org/schema/util/spring-util-2.5.xsd
<tx:attributes> Declares transactional rules for one or more methods. The utility namespace provides elements that make it possible
<tx:jta-transaction- Configures a JTA transaction manager, automatically to wire collections and other non-bean objects in Spring as if
manager> detecting WebLogic, WebSphere, or OC4J.
they were any other bean.
<tx:method> Describes transactional rules for a given method signature.
Util Namespace Diagram
TX Namespace Example
The following Spring configuration uses elements in the tx <util:constant>
namespace to configure transactional rules and boundaries:
<util:list>
<?xml version=”1.0” encoding=”UTF-8”?>
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” <util:map>
xmlns:tx=”http://www.springframework.org/schema/tx” <beans>
xmlns:aop=”http://www.springframework.org/schema/aop” <util:properties>
xsi:schemaLocation=”http://www.springframework.org/
schema/beans
<util:set>
http://www.springframework.org/schema/beans/spring-
beans-2.5.xsd
http://www.springframework.org/schema/aop <util:property-path>
http://www.springframework.org/schema/aop/spring-
aop-2.5.xsd
http://www.springframework.org/schema/tx Util Namespace Elements
http://www.springframework.org/schema/tx/spring-tx-
2.5.xsd”>
Element Description
<tx:jta-transaction-manager />
<util:constant> References a static field on a type and exposes its value as a bean.
<tx:advice id=”txAdvice”>
<tx:attributes> <util:list> Declares a list of values or references as a bean.
<tx:method name=”plunder*” propagation=”REQUIRED” />
<tx:method name=”*” propagation=”SUPPORTS” /> <util:map> Declares a map as a bean.
</tx:attributes>
<util:properties> Loads a java.util.Properties from a properties file and
</tx:advice>
exposes it as a bean.
<aop:config>
<aop:advisor <util:set> Declares a set as a bean.
pointcut=”execution(* ..Pirate.*(..))”
<util:property- References a bean property (or a nested property) and exposes
advice-ref=”txAdvice” />
path> that property as a bean itself.
</aop:config>
</beans>
Stereotyping Annotations
The util namespace, continued These annotations are used to stereotype classes with regard to
the application tier that they belong to. Classes that are annotated
Util Namespace Example, continued with one of these annotations will automatically be registered in
<util:list id=”piratePhrases”> the Spring application context if <context: component-scan> is
<value>Yo ho ho</value> in the Spring XML configuration.
<value>Yarr</value>
<value>Avast me hearties!</value> In addition, if a PersistenceExceptionTranslationPostProcessor
<value>Blow me down</value>
</util:list> is configured in Spring, any bean annotated with @Repository will
<util:constant id=”pirateCode” have SQLExceptions thrown from its methods translated into
static-field=”Pirate.PIRATE_CODE” /> one of Spring’s unchecked DataAccessExceptions.
<util:property-path id=”doubloonCount”
path=”pirate.treasure.doubloonCount” /> Annotation Use Description
element creates a reference to the constant (public static field) @Repository Type Stereotypes a component as a repository. Also
named PIRATE_CODE of the Pirate class. Finally, the <util:property- indicates that SQLExceptions thrown from the
component’s methods should be translated into
path> digs deep into the “pirate” bean, retrieving the value of Spring DataAccessExceptions.
the doubloonCount property of the treasure property of the bean
@Service Type Stereotypes a component as a service.
named “pirate”. In all three cases, the resulting values are exposed
as beans in the Spring context, suitable for injection into other beans.
Spring MVC Annotations
These annotations were introduced in Spring 2.5 to make it
Spring Annotations easier to create Spring MVC applications with minimal XML
configuration and without extending one of the many imple-
Historically, Spring configuration has primarily involved XML. mentations of the Controller interface.
But that is changing as Spring gradually embraces annotation-
driven configuration. As of Spring 2.5, there are 36 annotations Annotation Use Description
provided by Spring, not to mention annotations provided by @Controller Type Stereotypes a component as a Spring MVC
controller.
third party libraries and various Spring add-ons.
@InitBinder Method Annotates a method that customizes data
Context Configuration Annotations binding.
These annotations are used by Spring to guide creation and @ModelAttribute Parameter, When applied to a method, used to preload
Method the model with the value returned from
injection of beans. the method. When applied to a parameter,
binds a model attribute to the parameter.
Annotation Use Description
@RequestMapping Method, Maps a URL pattern and/or HTTP method to
@Autowired Constructor, Declares a constructor, field, setter method, Type a method or controller type.
Field, Method or configuration method to be autowired by
type. Items annotated with @Autowired do @RequestParam Parameter Binds a request parameter to a method
not have to be public. parameter.
@Configurable Type Used with <context:spring-configured> to @SessionAttributes Type Specifies that a model attribute should be
declare types whose properties should be stored in the session.
injected, even if they are not instantiated by
Spring. Typically used to inject the properties
of domain objects. JMX Annotations
@Order Type, Method, Defines ordering, as an alternative to These annotations, used with the <context:mbean-export>
Field implementing the org.springframework.core. element, declare bean methods and properties as MBean
Ordered interface.
operations and attributes.
@Qualifier Field, Guides autowiring to be performed by means
Parameter, Type, other than by type. Annotation Use Description
Annotation Type
@ManagedAttribute Method Used on a setter or getter method to
@Required Method (setters) Specifies that a particular property must be indicate that the bean’s property should be
injected or else the configuration will fail. exposed as an MBean attribute.
@Scope Type Specifies the scope of a bean, either @ManagedNotification Type Indicates a JMX notification emitted by a bean.
singleton, prototype, request, session, or
some custom scope. @ManagedNotifications Type Indicates the JMX notifications emitted by
a bean.
@Transactional Method, Declares transactional boundaries and rules @ManagedResource Type Specifies that all instances of a class should
Type on a bean and/or its methods. be exposed as MBeans.
Upcoming Refcardz:
tech facts at your fingertips
FREE
n
Dependency Injection in EJB3
n
jQuery Selectors
n
Windows PowerShell
n
Design Patterns
n
RSS and Atom
n
MS Silverlight 2.0
n
Flexible Rails:
n
NetBeans IDE 6 Getting
Flex 3 on Rails 2 Java Editor Hot
Tip Started with
n
Groovy Ajax
n
Getting Started with Eclipse
GWT Style, Configuration
and JSNI Reference
DZone, Inc.
ISBN-13: 978-1-934238-05-9
1251 NW Maynard
ISBN-10: 1-934238-05-8
Cary, NC 27513 50795
888.678.0399
The DZone Network is a group of free online services that aim to 919.678.0300
satisfy the information needs of software developers and architects. Refcardz Feedback Welcome
From news, blogs, tutorials, source code and more, DZone offers
$7.95
refcardz@dzone.com
everything technology professionals need to succeed. Sponsorship Opportunities
9 781934 238059
To quote PC magazine, “DZone is a developer’s dream.” sales@dzone.com
Copyright © 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, Version 1.0
mechanical, photocopying, or otherwise, without prior written permission of the publisher.