Spring Core

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.

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 
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.0.xsd">
               
     <context:annotation-config></context:annotation-config>
     <context:component-scan base-package="com.dineshonjava.sdnext">
     </context:component-scan>
     <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
     <context:property-placeholder location="classpath:jdbcConfig.properties">
     </context:property-placeholder>
</beans>

 

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:

Target:

        bean property setter methods
Desrcription- 
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:

Target:

        bean property setter methods, non-setter methods, constructor and properties
Desrcription- 

@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:

Target:

        bean property setter methods
Desrcription- 
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:

Target:

        on class marks
Desrcription- 
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:

Target:

        setter and non setter methods
Desrcription- 
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:

Target:

        Classes marked with stereotype annotations
Desrcription- 

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

 

Spring Related Topics you may like

 

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago