Spring Annotations Ref Card
Spring Annotations Ref Card
Spring Annotations Ref Card
CONTENTS INCLUDE:
n
Core Spring Annotations Spring MVC Annotations AspectJ Annotations JSR-250 Annotations Testing Annotations Hot Tips and more...
Spring Annotations
By Craig Walls
Autowiring Bean Properties, continued
@Autowired public void setTreasureMap(TreasureMap treasureMap) { this.treasureMap = treasureMap; } }
SPRING ANNOTATIONS
From its beginning, Springs most common means of configuration has been XML-based. But as developers grow weary of navigating through a seemingly endless maze of angle-brackets, some have started looking for other ways to wire the beans in their Spring-enabled applications. Spring has responded with several annotation-driven configuration options. In this reference card, you'll find a guide to all of the annotations supported in Spring 2.5.
and if you were to configure annotation configuration in Spring using the <context:annotation-configuration> element like this
<beans ... > <bean id="pirate" class="Pirate"> <constructor-arg value="Long John Silver" /> </bean> <bean id="treasureMap" class="TreasureMap" /> <context:annotation-config /> </beans>
then the treasureMap property will be automatically injected with a reference to a bean whose type is assignable to TreasureMap (in this case, the bean whose ID is treasureMap).
www.dzone.com
@Configurable
Type
@Order
@Qualifier @Required
To resolve any autowiring ambiguity, use the @Qualifier attribute with @Autowired.
@Autowired @Qualifier(mapToTortuga) private TreasureMap treasureMap;
@Scope
Type
Spring Annotations
A typical Spring bean might have its properties wired something like this:
<bean id=pirate class=Pirate> <constructor-arg value=Long John Silver /> <property name=treasureMap ref=treasureMap /> </bean>
But its also possible to have Spring automatically inject a beans properties from other beans in the context. For example, if the Pirate class were annotated with @Autowired like this
public class Pirate { private String name; private TreasureMap treasureMap; public Pirate(String name) { this.name = name; }
DZone, Inc.
|
Authoritative content Designed for developers Written by top experts Latest tools & technologies Hot tips & examples Bonus content online New issue every 1-2 weeks
2
tech facts at your fingertips
Spring Annotations
Hot Tip
Specifying Scope For Auto-Configured Beans By default, all beans in Spring, including auto-configured beans, are scoped as singleton. But you can specify the scope using the @Scope annotation. For example:
@Component @Scope(prototype) public class Pirate { ... }
In this case, the treasureMap property must be injected or else Spring will throw a BeanInitializationException and context creation will fail.
Stereotyping Annotations
These annotations are used to stereotype classes with regard to the application tier that they belong to. Classes that are annotated with one of these annotations will automatically be registered in the Spring application context if <context:component-scan> is in the Spring XML configuration. In addition, if a PersistenceExceptionTranslationPostProcessor is configured in Spring, any bean annotated with @Repository will have SQLExceptions thrown from its methods translated into one of Springs unchecked DataAccessExceptions.
Annotation @Component @Controller @Repository Use Type Type Type Description Generic stereotype annotation for any Spring-managed component. Stereotypes a component as a Spring MVC controller. Stereotypes a component as a repository. Also indicates that SQLExceptions thrown from the components methods should be translated into Spring DataAccessExceptions. Stereotypes a component as a service.
2. Or add a filter to <context:component-scan> to scan for annotations that it normally would not:
<context:component-scan base-package=com.habuma.pirates> <context:include-filter type=annotation expression=com.habuma.MyComponent /> <context:exclude-filter type=annotation expression= "org.springframework.stereotype.Component" /> </context:component-scan>
@Service
Type
In this case, the @MyComponent custom annotation has been added to the list of annotations that are scanned for, but @Component has been excluded (that is, @Componentannotated classes will no longer be autoregistered). Regardless of which option you choose, you should be able to autoregister beans by annotating their classes with the custom annotation:
@MyComponent public class Pirate { }
The base-package annotation tells Spring to scan com.habuma. pirates and all of its subpackages for beans to automatically register. You can specify a name for the bean by passing it as the value of @Component.
@Component(jackSparrow) public class Pirate { }
DZone, Inc.
www.dzone.com
3
tech facts at your fingertips
Spring Annotations
In addition to autoregistering @Component-annotated beans, <context:component-scan> also autoregisters beans that are annotated with @Controller. Well see a few examples of @Controller-annotated classes in a moment. But first, well also need to tell Spring to honor the other Spring MVC annotations. For that well need <context:annotation-config> :
<context:annotation-config/>
If you use a conventions-based view resolver, such as Spring's UrlBasedViewResolver or InternalResourceViewResolver, along with <context:component-scan> and <context:annotation-config>, you can grow your application indefinitely without ever touching the Spring XML again.
Creating a Simple MVC Controller
The following HomePage class is annotated to function as a Spring MVC controller:
@Controller @RequestMapping("/home.htm") public class HomePage { @RequestMapping(method = RequestMethod.GET) public String showHomePage(Map model) { List<Pirate> pirates = pirateService. getPirateList(); model.add(pirateList, pirates); return "home"; } @Autowired PirateService pirateService; }
Hot Tip
Here the @RequestMapping annotation is applied to two different methods. The setupForm() method is annotated to handle HTTP GET requests while the addPirate() method will handle HTTP POST requests. Meanwhile, the @ModelAttribute is also pulling double duty by populating the model with a new instance of Pirate before the form is displayed and then pulling the Pirate from the model so that it can be given to addPirate() for processing.
Transaction Annotations
The @Transactional annotation is used along with the <tx:annotation-driven> element to declare transactional boundaries and rules as class and method metadata in Java.
Annotation @Transactional Use Method, Type Description Declares transactional boundaries and rules on a bean and/or its methods.
There are several important things to point out here. First, the HomePage class is annotated with @Controller so that it will be autoregistered as a bean by <context:component-scan>. It is also annotated with @RequestMapping, indicating that this controller will respond to requests for /home.htm. Within the class, the showHomePage() method is also annotated with @RequestMapping. In this case, @RequestMapping indicates that HTTP GET requests to /home.htm will be handled by the showHomePage() method.
The <tx:annotation-driven> element tells Spring to keep an eye out for beans that are annotated with @Transactional. In addition, youll also need a platform transaction manager bean declared in the Spring context. For example, if your application uses Hibernate, youll want to include the HibernateTransactionManager:
<bean id=transactionManager lass=org.springframework.orm.hibernate3. c HibernateTransactionManager> <property name=sessionFactory ref=sessionFactory /> </bean>
|
www.dzone.com
4
tech facts at your fingertips
Spring Annotations
At the class level, @Transactional is declaring that all methods should support transactions and be read-only. But, at the method-level, @Transactional declares that the storeTreasure() method requires a transaction and is not read-only. Note that for transactions to be applied to @Transactionalannotated classes, those classes must be wired as beans in Spring.
@Pointcut
Method
JMX Annotations
These annotations, used with the <context:mbean-export> element, declare bean methods and properties as MBean operations and attributes.
Annotations @ManagedAttribute Use Method Description Used on a setter or getter method to indicate that the beans property should be exposed as a MBean attribute. Indicates a JMX notification emitted by a bean. Indicates the JMX notifications emitted by a bean. Specifies that a method should be exposed as a MBean operation. Used to provide a description for an operation parameter. Provides descriptions for one or more operation parameters. Specifies that all instances of a class should be exposed a MBeans.
Whats important to note, however, is that while you can use AspectJ annotations to define Spring aspects, those aspects will be defined in the context of Spring AOP and will not be handled by the AspectJ runtime. This is significant because Spring AOP is limited to proxying method invocations and does not provide for the more exotic pointcuts (constructor interception, field interception, etc.) offered by AspectJ.
Annotating Aspects
To use AspectJ annotations to create Spring aspects, youll first need to provide a bit of Spring XML plumbing:
<beans xmlns="http://www.springframework.org/schema/ beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" si:schemaLocation="http://www.springframework.org/ x schema/beans ttp://www.springframework.org/schema/beans/ h spring-beans-2.5.xsd http://www.springframework.org/schema/aop ttp://www.springframework.org/schema/aop/springh aop-2.5.xsd"> <aop:aspectj-autoproxy/> </beans>
Then, you can annotate any of your Spring-managed beans to be exported as MBeans:
@ManagedResource(objectName="pirates:name=PirateService") public interface PirateService { @ManagedOperation( description="Get the pirate list") public List<Pirate> getPirateList(); }
The <aop:aspectj-autoproxy> element tells Spring to watch for beans annotated with AspectJ annotations and, if it finds any, to use them to create aspects. Then you can annotate bean classes to be aspects:
@Aspect public class ChantySinger { @Pointcut(execution(* Pirate.plunder(..))) public void plunderPC() {} @Before(plunderPC()) public void singYoHo() { } @AfterReturning(plunderPC()) public void singAPiratesLifeForMe() { } }
Here, the PirateService has been annotated to be exported as a MBean and its getPirateList() method is a managed operation.
ASPECTJ ANNOTATIONS
For defining aspects, Spring leverages the set of annotations provided by AspectJ.
Annotation @Aspect @After Use Type Method Description Declares a class to be an aspect. Declares a method to be called after a pointcut completes.
This simple annotation-based aspect has a pointcut that is triggered by the execution of a plunder() method on the Pirate class. Before the Pirate.plunder() method is executed, the singYoHo() method is called. Then, after the Pirate.plunder() method returns successfully, the singAPiratesLifeForMe()
|
DZone, Inc.
www.dzone.com
5
tech facts at your fingertips
Spring Annotations
TESTING ANNOTATIONS
These annotations are useful for creating unit tests in the JUnit 4 style that depend on Spring beans and/or require a transactional context.
Annotation @AfterTransaction Use Method Description Used to identify a method to be invoked after a transaction has completed. Used to identify a method to be invoked before a transaction starts. Configures a Spring application context for a test. Indicates that a method dirties the Spring container and thus it must be rebuilt after the test completes. Indicates that the test method is expected to throw a specific exception. The test will fail if the exception is not thrown. Indicates that the test class or method is enabled for a specific profile configuration. Indicates that a test method must not execute in a transactional context. Identifies an implementation of a profile value source. The absence of this annotation will cause profile values to be loaded from system properties. Indicates that the test method must be repeated a specific number of times. Specifies whether or not the transaction for the annotated method should be rolled back or not. Identifies zero or more test execution listeners for a test class. Specifies a time limit for the test method. If the test does not complete before the time has expired, the test will fail. Configures test classes for transactions, specifying the transaction manager and/or the default rollback rule for all test methods in a test class.
@BeforeTransaction @ContextConfiguration
JSR-250 ANNOTATIONS
In addition to Springs own set of annotations, Spring also supports a few of the annotations defined by JSR-250, which is the basis for the annotations used in EJB 3.
Annotation @PostConstruct Use Method Description Indicates a method to be invoked after a bean has been created and dependency injection is complete. Used to perform any initialization work necessary. Indicates a method to be invoked just before a bean is removed from the Spring context. Used to perform any cleanup work necessary. Indicates that a method or field should be injected with a named resource (by default, another bean).
@DirtiesContext
@ExpectedException
Method
@IfProfileValue
@NotTransactional
@PreDestroy
Method
@ProfileValueSourceConfiguration
Type
@Resource
Method, Field
@Repeat
Method
@Rollback
Method
@TestExecutionListeners @Timed
Type Method
In this case, Spring will attempt to wire the treasureMap property with a reference to a bean whose ID is treasureMap. If youd rather explicitly choose another bean to wire into the property, specify it to the name attribute:
public class Pirate { @Resource(name=mapToSkullIsland) private TreasureMap treasureMap; }
@TransactionConfiguration
Type
In this case, the Spring test runner will try to load a Spring application context from a file named PirateTest-context.xml. If youd rather specify one or more XML files to load the application context from, you can do that with @ContextConfiguration:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "pirates.xml" }) public class PirateTest { }
As annotated, the wakeUp() method will be invoked just after Spring instantiates the bean and goAway() will be invoked just before the bean is removed from the Spring container.
DZone, Inc.
|
With test configured to load a Spring application context, you now may request that Spring autowire properties of the test class with beans from the Spring context:
www.dzone.com
6
tech facts at your fingertips
Spring Annotations
In this case, the pirate and treasureMap properties will be wired with the beans whose ID are pirate and treasureMap, respectively.
RECOMMENDED BOOK
Spring in Action, 2nd Edition is a practical and comprehensive guide to the Spring Framework, the framework that forever changed enterprise Java development. Whats more, its also the first book to cover the new features and capabilities in Spring 2.
Craig Walls
Craig Walls is a Texas-based software developer with more than 13 years experience working in the telecommunication, financial, retail, educational, and software industries. Hes a zealous promoter of the Spring Framework, speaking frequently at local user groups and conferences and writing about Spring on his blog. When hes not slinging code, Craig spends as much time as he can with his wife, two daughters, six birds, three dogs, and an ever-fluctuating number of tropical fish.
Publications
n n
Projects
n
Committer to XDoclet project; Originator of Portlet and Spring modules for XDoclet
Blog
n
BUY NOW
books.dzone.com/books/spring-in-action
Available:
Essential Ruby Essential MySQL
JUnit and EasyMock Getting Started with MyEclipse Spring Annotations Core Java Core CSS: Part II PHP Getting Started with JPA JavaServer Faces Core CSS: Part I Struts2 Core .NET Very First Steps in Flex C# Groovy NetBeans IDE 6.1 Java Editor RSS and Atom
FREE
Design Patterns
Published June 2008
DZone communities deliver over 4 million pages each month to more than 1.7 million software developers, architects and decision makers. DZone offers something for everyone, including news, tutorials, cheatsheets, blogs, feature articles, source code and more. DZone is a developers dream, says PC Magazine.
9 781934 238295
Version 1.0
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, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Reference: Spring in Action, 2nd Edition, Craig Walls, Manning Publications, 2007.
$7.95