Spring Annotations

Spring’s most common means of configuration has been XML-based. Annotations since Spring 2.5 provide a lot of context in their declaration, leading to shorter and more concise configuration. However, XML excels at wiring up components without touching their source code or recompiling them. Some developers prefer having the wiring close to the source while others argue that annotated classes are no longer POJOs and, furthermore, that the configuration becomes decentralized and harder to control.

Annotations are implicitly registered by including the following tag in an XML-based Spring configuration (notice the inclusion of the context namespace):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <context:annotation-config/>
    <context:component-scan base-package="...specify your package name..." />
</beans>

 

Spring supports both Annotation based and XML based configurations. You can even mix them together. Annotation injection is performed before XML injection, thus the latter configuration will override the former for properties wired through both approaches.

Core Spring Annotations

Context Configuration Annotations

These annotations are used by Spring to guide creation and injection of beans.

ANNOTATION USE DESCRIPTION
@Autowired Constructor, Field, Method Declares a constructor, field, setter method, or configuration method to be autowired by type. Items annotated with @Autowired do not have to be public.
@Configurable Type Used with <context:springconfigured> to declare types whose properties should be injected, even if they are not instantiated by Spring. Typically used to inject the properties of domain objects.
@Order Type, Method, Field Defines ordering, as an alternative to implementing the org. springframework.core.Ordered interface.
@Qualifier Field, Parameter, Type, Annotation Type Guides autowiring to be performed by means other than by type.
@Required Method (setters) Specifies that a particular property must be injected or else the configuration will fail.
@Scope Type Specifies the scope of a bean, either singleton, prototype, request, session, or some custom scope.

@Autowired

Let Spring auto-wire other beans into your classes using @Autowired annotation.

@Service
public class CompanyServiceImpl implements CompanyService {
 
  @Autowired
  private CompanyDAO companyDAO;
   
  ...
}

Spring beans can be wired by name or by type.

  • @Autowire by default is a type driven injection. @Qualifier spring annotation can be used to further fine-tune autowiring.
  • @Resource (javax.annotation.Resource) annotation can be used for wiring by name.

Beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans, referring to the specific collection or map bean by unique name.

Mode Explanation
no (Default) No autowiring. Bean references must be defined via a ref element. Changing the default setting is not recommended for larger deployments, because specifying collaborators explicitly gives greater control and clarity. To some extent, it documents the structure of a system.
byName Autowiring by property name. Spring looks for a bean with the same name as the property that needs to be autowired. For example, if a bean definition is set to autowire by name, and it contains a master property (that is, it has a setMaster(..) method), Spring looks for a bean definition named master, and uses it to set the property.
byType Allows a property to be autowired if exactly one bean of the property type exists in the container. If more than one exists, a fatal exception is thrown, which indicates that you may not use byType autowiring for that bean. If there are no matching beans, nothing happens; the property is not set.
constructor Analogous to byType, but applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.

@Scope

As with Spring-managed components in general, the default and most common scope for autodetected components is singleton. To change this default behavior, use @Scope spring annotation.

@Component
@Scope("request")
public class ContactResource {
...
}

Similarly, you can annotate your component with @Scope(“prototype”) for beans with prototype scopes. Please note that the dependencies are resolved at instantiation time. For prototype scope, it does NOT create a new instance at runtime more than once. It is only during instantiation that each bean is injected with a separate instance of prototype bean.

The following scopes are supported out of the box. You can also create a custom scope.

Scope Description
singleton (Default) Scopes a single bean definition to a single object instance per Spring IoC container.
prototype Scopes a single bean definition to any number of object instances.
request Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

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 Spring’s unchecked DataAccessExceptions.

ANNOTATION USE DESCRIPTION
@Component Type Generic stereotype annotation for any Spring-managed component.
@Controller Type Stereotypes a component as a Spring MVC controller.
@Repository Type Stereotypes a component as a repository. Also indicates that SQLExceptions thrown from the component’s methods should be translated into Spring DataAccessExceptions.
@Service Type Stereotypes a component as a service.

@Component

Annotate your other components (for example REST resource classes) with @Component.

@Component
public class ContactResource {
...
}

@Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases, for example, in the persistence, service, and presentation layers, respectively.

Spring Component Annotations

@Repository

Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.

@Repository
public class CompanyDAOImpl implements CompanyDAO {
...
}

 

@Service

Annotate all your service classes with @Service. All your business logic should be in Service classes.

@Service
public class CompanyServiceImpl implements CompanyService {
...
}

 

 

Spring MVC Annotations

These annotations were introduced in Spring 2.5 to make it easier to create Spring MVC applications with minimal XML configuration and without extending one of the many implementations of the Controller interface.

ANNOTATION USE DESCRIPTION
@Controller Type Stereotypes a component as a Spring MVC controller.
@InitBinder Method Annotates a method that customizes data binding.
@ModelAttribute Parameter, Method When applied to a method, used to preload the model with the value returned from the method. When applied to a parameter, binds a model attribute to the parameter. table
@RequestMapping Method, Type Maps a URL pattern and/or HTTP method to a method or controller type.
@RequestParam Parameter Binds a request parameter to a method parameter.
@SessionAttributes Type Specifies that a model attribute should be stored in the session.
@PathVariable Parameter Binds a request path variable to a method parameter
@ModelAttribute Parameter Binds a model from the post request to a method parameter

@Controller

Annotate your controller classes with @Controller. 

@Controller
public class CompanyController {
...
}

@RequestMapping

You use the @RequestMapping spring annotation to map URLs onto an entire class or a particular handler method. Typically the class-level annotation maps a specific request path (or path pattern) onto a form controller, with additional method-level annotations narrowing the primary mapping.

@Controller
@RequestMapping("/company")
public class CompanyController {
 
  @Autowired
  private CompanyService companyService;
...
}

@RequestParam

You can bind request parameters to method variables using spring annotation @RequestParam.

@Controller
@RequestMapping("/company")
public class CompanyController {
 
  @Autowired
  private CompanyService companyService;
 
  @RequestMapping("/companyList")
  public String listCompanies(Map<String, Object> map, 
            @RequestParam int pageNum) {
    map.put("pageNum", pageNum);
    map.put("companyList", companyService.listCompanies(pageNum));
    return "companyList";
  }
...
}

Similarly, you can use spring annotation @RequestHeader to bind request headers.

@SessionAttributes

@SessionAttributes spring annotation declares session attributes. This will typically list the names of model attributes which should be transparently stored in the session, serving as form-backing beans between subsequent requests.

@Controller
@RequestMapping("/company")
@SessionAttributes("company")
public class CompanyController {
 
  @Autowired
  private CompanyService companyService;
...
}

@SessionAttribute works as follows:

  • @SessionAttribute is initialized when you put the corresponding attribute into model (either explicitly or using @ModelAttribute-annotated method).
  • @SessionAttribute is updated by the data from HTTP parameters when controller method with the corresponding model attribute in its signature is invoked.
  • @SessionAttributes are cleared when you call setComplete() on SessionStatus object passed into controller method as an argument.

The following listing illustrate these concepts. It is also an example for pre-populating Model objects.

@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {
 
    @ModelAttribute("types")
     
    public Collection<PetType> populatePetTypes() {
        return this.clinic.getPetTypes();
    }
     
    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("pet") Pet pet, 
            BindingResult result, SessionStatus status) {
        new PetValidator().validate(pet, result);
        if (result.hasErrors()) {
            return "petForm";
        }else {
            this.clinic.storePet(pet);
            status.setComplete();
            return "redirect:owner.do?ownerId="
                + pet.getOwner().getId();
        }
    }
}

 

@PathVariable

You can use the @PathVariable spring annotation on a method argument to bind it to the value of a URI template variable. In our example below, a request path of /company/empeccable will bind companyName variable with ’empeccable’ value.

@Controller
@RequestMapping("/company")
public class CompanyController {
 
  @Autowired
  private CompanyService companyService;
 
  @RequestMapping("{companyName}")
  public String getCompany(Map<String, Object> map, 
            @PathVariable String companyName) {
    Company company = companyService.findByName(companyName);
    map.put("company", company);
    return "company";
  }
...
}

 @ModelAttribute

An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model. Once present in the model, the argument’s fields should be populated from all request parameters that have matching names. This is known as data binding in Spring MVC, a very useful mechanism that saves you from having to parse each form field individually.

@Controller
@RequestMapping("/company")
public class CompanyController {
 
  @Autowired
  private CompanyService companyService;
 
  @RequestMapping("/add")
  public String saveNewCompany(@ModelAttribute Company company) {
    companyService.add(company);
    return "redirect:" + company.getName();
  }
...
}

 

 

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 USE DESCRIPTION
@Transactional Method, Type Declares transactional boundaries and rules on a bean and/or its methods.

@Transactional

Configure your transactions with @Transactional spring annotation.

@Service
public class CompanyServiceImpl implements CompanyService {
 
  @Autowired
  private CompanyDAO companyDAO;
 
  @Transactional
  public Company findByName(String name) {
 
    Company company = companyDAO.findByName(name);
    return company;
  }
  ...
}

The default @Transactional settings are as follows:

  • Propagation setting is PROPAGATION_REQUIRED.
  • Isolation level is ISOLATION_DEFAULT.
  • Transaction is read/write.
  • Transaction timeout defaults to the default timeout of the underlying transaction system, or to none if timeouts are not supported.
  • Any RuntimeException triggers rollback, and any checked Exception does not.

These default settings can be changed using various properties of the @Transactional spring annotation. Specifying the @Transactional annotation on the bean class means that it applies to all applicable business methods of the class. Specifying the annotation on a method applies it to that method only. If the annotation is applied at both the class and the method level, the method value overrides if the two disagree. To activate processing of Spring’s @Transactional annotation, use the <tx:annotation-driven/> element in your spring’s configuration file.

 

JMX Annotations

These annotations, used with the <context:mbean-export> element, declare bean methods and properties as MBean operations and attributes.

ANNOTATIONS USE DESCRIPTION
@ManagedAttribute Method Used on a setter or getter method to indicate that the bean’s property should be exposed as a MBean attribute.
@ManagedNotification Type Indicates a JMX notification emitted by a bean.
@ManagedNotifications Type Indicates the JMX notifications emitted by a bean.
@ManagedOperation Method Specifies that a method should be exposed as a MBean operation.
@ManagedOperationParameter Method Used to provide a description for an operation parameter.
@ManagedOperationParameters Method Provides descriptions for one or more operation parameters.
@ManagedResource Type Specifies that all instances of a class should be exposed a MBeans.
 

Aspect Annotations

For defining aspects, Spring leverages the set of annotations provided by AspectJ.

ANNOTATION USE DESCRIPTION
@Aspect Type Declares a class to be an aspect.
@After Method Declares a method to be called after a pointcut completes.
@AfterReturning Method Declares a method to be called after a pointcut returns successfully.
@AfterThrowing Method Declares a method to be called after a pointcut throws an exception.
@Around Method Declares a method that will wrap the pointcut.
@Before Method Declares a method to be called before proceeding to the pointcut.
@DeclareParents Static Field Declares that matching types should be given new parents,that is, it introduces new functionality into matching types.
@Pointcut Method Declares an empty method as a pointcut placeholder method.

What’s 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.

 

JSR-250 Annotations

In addition to Spring’s 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 USE DESCRIPTION
@PostConstruct Method Indicates a method to be invoked after a bean has been created and dependency injection is complete. Used to perform any initialization work necessary.
@PreDestroy Method Indicates a method to be invoked just before a bean is removed from the Spring context. Used to perform any cleanup work necessary.
@Resource Method, Field Indicates that a method or field should be injected with a named resource (by default, another bean).
 

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 USE DESCRIPTION
@AfterTransaction Method Used to identify a method to be invoked after a transaction has completed.
@BeforeTransaction Method Used to identify a method to be invoked before a transaction starts.
@ContextConfiguration Type Configures a Spring application context for a test.
@DirtiesContext Method Indicates that a method dirties the Spring container and thus it must be rebuilt after the test completes.
@ExpectedException Method Indicates that the test method is expected to throw a specific exception. The test will fail if the exception is not thrown.
@IfProfileValue Type, Method Indicates that the test class or method is enabled for a specific profile configuration.
@NotTransactional Method Indicates that a test method must not execute in a transactional context.
@ProfileValueSourceConfiguration Type Identifies an implementation of a profile value source. The absence of this annotation will cause profile values to be loaded from system properties.
@Repeat Method Indicates that the test method must be repeated a specific number of times.
@Rollback Method Specifies whether or not the transaction for the annotated method should be rolled back or not.
@TestExecutionListeners Type Identifies zero or more test execution listeners for a test class.
@Timed Method Specifies a time limit for the test method. If the test does not complete before the time has expired, the test will fail.
@TransactionConfiguration Type Configures test classes for transactions, specifying the transaction manager and/or the default rollback rule for all test methods in a test class.

Spring jUnit Annotations

@RunWith

When a class is annotated with @RunWith or extends a class annotated with @RunWith, JUnit will invoke the class it references to run the tests in that class instead of the runner built into JUnit. Let us configure jUnit to use Spring jUnit Class runner.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring-servlet-test.xml" })
public class CompanyServiceTest {
...
}

@ContextConfiguration

Set the spring ApplicationContext for your test classes using @ContextConfiguration annotation.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring-servlet-test.xml" })
public class CompanyServiceTest {
...
}

 

@ContextConfiguration provides support for inheriting resource locations or configuration classes declared by superclasses by default.

@Test

Annotate all your jUnit unit tests with @Test. Also note that we can wire other spring beans in our jUnit test classes using @Autowired annotation.

@Autowired
private CompanyService companyService;
 
@Test
public void testFindByName() {
  Company company = companyService.findByName("techferry");
  if (company != null) {
    assertEquals("prospect", company.getStatus().getName());
  }
}

 

@DirtiesContext

Annotate @DirtiesContext to indicate that it dirties the ApplicationContext. This will trigger context reloading before execution of next test.

@Timed

Indicates that the annotated test method must finish execution in a specified time period (in milliseconds). If the text execution time exceeds the specified time period, the test fails.

@Timed(millis=1000)

 

Website

References

  • Spring Annotations – Dzone Refcardz

    Spring Annotations From its beginning, Spring’s 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 DZone Refcard, you’ll find a guide to all of the annotations supported in Spring 2.5. This card also covers Core Spring Annotations, Spring MVC Annotations, AspectJ Annotations, JSR-250 Annotations, Testing Annotations, Hot Tips and more.

    Source: dzone.com/refcardz/spring-annotations

  • Spring Annotations

    Spring Annotations: This tutorial is part 1 of 5-part tutorial on JEE annotations. It contains usage instructions, code examples and tips on spring annotations.

    Source: www.techferry.com/articles/spring-annotations.html