Annotations in Spring and Based Configuration

In Spring 2.0 introduced support for various annotations for configuration purposes, such as @Transactional, @Required and @PersistenceContext /@PersistenceUnit. Spring 2.5 introduces support for a complete set of configuration annotations: @Autowired in combination with support for the JSR-250 annotations @Resource, @PostConstruct and @PreDestroy .

As of Spring 2.5, it is now possible to follow that same general approach to drive Spring's dependency injection.Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

Annotation injection is performed before XML injection, thus the latter configuration will override the former for properties wired through both approaches.
Popular Spring Tutorials
  1. Spring Tutorial
  2. Spring MVC Web Tutorial
  3. Spring Boot Tutorial
  4. Spring JDBC Tutorial
  5. Spring AOP Tutorial
  6. Spring Security Tutorial
Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file. So consider to have following configuration file in case you want to use any annotation in your Spring application.
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans 
     <context:component-scan base-package="com.dineshonjava.sdnext">
     <context:property-placeholder location="classpath:jdbcConfig.properties">
Now let me explain the new configurations in the above Spring context file(spring.xml). The <context:annotation-config/> element is used to automatically register all of Spring's standard post-processors for annotation-based configuration.

Element : annotation-config
Activates various annotations to be detected in bean classes: Spring's @Required and @Autowired, as well as JSR  250's @PostConstruct, @PreDestroy and @Resource (if available), JAX-WS's @WebServiceRef (if available), EJB3's  @EJB (if available), and JPA's @PersistenceContext and @PersistenceUnit (if available). Alternatively, you may choose to activate the individual BeanPostProcessors for those annotations.

Note: This tag does not activate processing of Spring's @Transactional or EJB3's @TransactionAttribute annotation. Consider the use of the <tx:annotation-driven> tag for that purpose.

The <context:component-scan base-package="com.dineshonjava.sdnext"/> element is used to enable autodetection of the stereotyped classes in the package "com.dineshonjava.sdnext". AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor are both included implicitly when using the component-scan element, the <context:annotation-config/> element can be omitted.

The properties for the data source are taken from the jdbcConfig.properties file in the classpath. The property placeholders are configured with the <context:property-placeholder/> element.

The <aop:aspectj-autoproxy/> element is used to enable @AspectJ support in Spring.

Element<context:load-time-weaver/> Activates a Spring LoadTimeWeaver for this application context, available as a bean with the name "loadTimeWeaver". Any bean that implements the LoadTimeWeaverAware interface will then receive the LoadTimeWeaver reference automatically; for example, Spring's JPA bootstrap support. The default weaver is determined automatically. As of Spring 2.5: detecting Sun's GlassFish, Oracle's OC4J, Spring's VM agent and any ClassLoader supported by pring's ReflectiveLoadTimeWeaver (for example, the TomcatInstrumentableClassLoader). The activation of AspectJ load-time weaving is specified via a simple flag (the 'aspectj-weaving' attribute), with the AspectJ class transformer registered through Spring's LoadTimeWeaver. AspectJ weaving will be activated by default if a "META-INF/aop.xml" resource is present in the classpath. This also activates the current application context for applying dependency injection to non-managed classes that are instantiated outside of the Spring bean factory (typically classes annotated with the @Configurable annotation). This will only happen if the AnnotationBeanConfigurerAspect is on the classpath (i.e. spring-aspects.jar), effectively activating "spring-configured" by default.

Let us see few important annotations to understand how they work:

Annotation @Required:


        bean property setter methods
The @Required annotation is used to specify that the value of a bean property is required to be dependency injected. That means, an error is caused if a value is not specified for that property. 

Annotation @Autowired:


        bean property setter methods, non-setter methods, constructor and properties
@Autowired may also be used for well-known "resolvable dependencies": the BeanFactory interface, the ApplicationContext interface, the ResourceLoader interface, the ApplicationEventPublisher interface and the MessageSource interface.

Annotation @Qualifier:


        bean property setter methods
There may be a situation when you create more than one bean of the same type and want to wire only one of them with a property, in such case you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired. Below is an example to show the use of @Qualifier annotation.

Annotation @Aspect:


        on class marks
To use @AspectJ aspects in a Spring configuration you need to enable Spring support for configuring Spring AOP based on @AspectJ aspects, and autoproxying beans based on whether or not they are advised by those aspects. By autoproxying we mean that if Spring determines that a bean is advised by one or more aspects, it will automatically generate a proxy for that bean to intercept method invocations and ensure that advice is executed as needed.

JSR-250 Annotations:


        setter and non setter methods
Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations. JSR 250, as a Java Specification Request, has the objective to define a set of annotations that address common semantic concepts and therefore can be used by many Java EE and Java SE components. This is to avoid redundant annotations across those components. JSR 250 was released on the 11th 05 2006. As Declarative annotation-driven configuration is more and more used in Java frameworks and applications, e.g. Spring makes more components of its framework configurable via annotations, the importance of JSR 250 is likely to increase in the future.

Stereotype Annotations:


        Classes marked with stereotype annotations
Classes marked with stereotype annotations are candidates for auto-detection by Spring when using annotation-based configuration and classpath scanning.

The @Component annotation is the main stereotype that indicates that an annotated class is a "component".

The @Service stereotype annotation used to decorate the Service implementation related class is a specialized form of the @Component annotation. It is appropriate to annotate the service-layer classes with @Service to facilitate processing by tools or anticipating any future service-specific capabilities that may be added to this annotation.

The @Repository annotation is yet another stereotype that was introduced in Spring 2.0 itself. A class that serves in the persistence layer of the application as a data access object (DAO), otherwise known as a repository in some other technologies.

@Controller A controller component in the presentation layer of the application, as it relates to a MVC-designed application

                          << Previous || Next >>