Spring Configuration With Annotations
What are Annotations?
Annotations are a powerful features of java included in JDK 1.5 with the main objective to make the development easier.Annotations are special labels added to java classes. It provides the meta-data about the class. For example meta-data of shoes can be size of the shoes, SKU of the shoes, Style of the shoes and so on.
Annotations can be applied to variables, parameters, field declarations, methods and constructors.
Annotations are processed at compile time or run-time for special processing.
What are Annotations?
Annotations are a powerful features of java included in JDK 1.5 with the main objective to make the development easier.Annotations are special labels added to java classes. It provides the meta-data about the class. For example meta-data of shoes can be size of the shoes, SKU of the shoes, Style of the shoes and so on.
Annotations can be applied to variables, parameters, field declarations, methods and constructors.
Annotations are processed at compile time or run-time for special processing.
Annotations in Spring :
Spring provides annotation based configuration as an alternative to XML. In annotation based configuration, the configuration is moved into the component class itself by using annotations on the relevant class, method or field declaration.
Why Spring Configuration with Annotations ?
Both the approaches are fine but if your project is very large and it contains large no of beans, in this case listing the beans in XML config file reuires more effort.Annotations minimizes the XML configuration.
Switching On Annotation Wiring in Spring
By default Annotation wiring is not turnrd on in the Spring. It needs to be switched on in the Spring configuration file by using context:annotation-config or context:component-scan.
<context:annotation-config/>
<context:annotation-config/> tag activates the annotation of the beans which is already registered in the application context. It doesn’t bother how it is registered if it is by <context:component-scan> or defined in the xml itself.
Enabling annotations in spring is very simple, you need to add only one line of code in your context file to enable them.
<context:annotation-config/>
Sample Application context file is given below.
application-context.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/>
<bean id="normalUser" class="com.jwt.spring.NormalUser"></bean>
<bean id="tempUser" class="com.jwt.spring.TempUser"></bean>
<bean id="superUser" class="com.jwt.spring.SuperUser"></bean>
</beans>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/> <bean id="normalUser" class="com.jwt.spring.NormalUser"></bean> <bean id="tempUser" class="com.jwt.spring.TempUser"></bean> <bean id="superUser" class="com.jwt.spring.SuperUser"></bean> </beans>
After annotation wiring is turned on and the bean class is annotated, spring automatically wires values into proprties, methods and constructors.
<context:annotation-config/>
mainly activates the 4 types of BeanPostProcessors
.
- CommonAnnotationBeanPostProcessor: @PostConstruct, @PreDestroy, @Resource
- AutowiredAnnotationBeanPostProcessor : @Autowired, @Value, @Inject, @Qualifier, etc
- RequiredAnnotationBeanPostProcessor : @Required annotation
- PersistenceAnnotationBeanPostProcessor :@PersistenceUnit and @PersistenceContext annotations
Let’s see an example of annotation-config
.
Author.java
package com.jwt.spring; public class Author { private String name; private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Author[Name=" + name + ", Address=" + address + "]"; } }
Book.java
package com.jwt.spring; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; public class Book { private Author author; private String isbn; private String year; public Author getAuthor() { return author; } @Autowired public void setAuthor(Author author) { this.author = author; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } @Override public String toString() { return "Book[ISBN=" + isbn + ", Author=" + author + ", Year=" + year + "]"; } }
application-Context.xml
Now to enable annotations you just need to write the below line in your context file:
<context:annotation-config/>
Here is your application context file.
<?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-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <context:annotation-config /> <bean id="book" class="com.jwt.spring.Book"> <property name="isbn" value="80-000-000" /> <property name="year" value="2016" /> </bean> <bean id="author" class="com.jwt.spring.Author"> <property name="address" value="OMR Chennai" /> <property name="name" value="Mukesh" /> </bean> </beans>
Test.java
package com.jwt.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "application-context.xml"); Book book = (Book) context.getBean("book"); System.out.println(book); } }
Output:
Book[ISBN=80-000-000, Author=Author[Name=Mukesh, Address=OMR Chennai], Year=2016]
In the above example Book is wired with an Author without using <property>. We used @Autowired
annotation to wire Author
property of Book
bean.
<context:component-scan>
<context:component-scan>
informs container to automatically discover and declare the beans. This means beans in the Spring Application can be declared and wired without using <bean>
.
scan packages and classes within given base packages then find and register beans into ApplicationContext.It does all things that <context:annotation-config/> is supposed to do. So if you have used annotation for example, @Autowired in your bean and <context:component-scan/> in context xml then You do not require to use <context:annotation-config/>
For example consider the sample application context file as given below.
application-context.xml
<?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.jwt.spring" /> </beans>
<context:component-scan/>
scans a package and all of its subpackages, looking for classes that could be automatically registered as beans in the Spring container. The <base-package>
attribute tells <context:component-scan/>
the package to begin its scan from.
The value of <base-package>
attribute is fully qualified package name of the bean classes. We can pass more than one package names by comma separated like the below one.
<context:component-scan base-package="package1, package2"/>
<context:component-scan/>
looks for classes that are annotated with one of the following annotations.
- @Component
- @Controller
- @Repository
- @Service
@Component:
The @Component
annotation marks a java class as a bean so the component-scanning mechanism of spring can pick it up and pull it into the application context. To use this annotation, apply it over class as below:
@Component public class EmployeeDAOImpl implements EmployeeDAO { ... }
@Repository:
In Spring use of @Component
is enough but you can use more suitable annotation that provides additional benefits specifically for DAOs i.e. @Repository
annotation. The @Repository
annotation is a specialization of the @Component
annotation with similar use and functionality. In addition to importing the DAOs into the DI container, it also makes the unchecked exceptions which may thrown from DAO methods are eligible for translation into Spring DataAccessException.
@Service:
@Service
indicates a service component in the business layer. @Service
serves as a specialization of @Component
. The service layer class can be annotated with @Component
, but by annotating them with @Service
, the classes are more properly suited for processing by tools. Also associating with aspects as @Service
makes an ideal target for pointcuts.
@Controller:
@Controller
annotation marks a class as a Spring Web MVC controller. This is also specialization of @Component
, so beans marked with it are automatically imported into the DI container.
Note:- Example of using these annotations are covered in CRUD Example using Spring MVC.
@Autowired :
In Spring bean dependencies are defined in the XML files, the same can be automatically detected by the Spring container by using the @Autowired annotation. This would eliminate using the XML configurations.
Complete @Autowired
annotations tutorial is covered in @Autowired Annotation in Spring.
@Qualifier:
There may be scenarios when we create more than one bean of the same type and want to wire only one of them with a property. This can be controlled using @Qualifier
annotation along with the @Autowired
annotation.
Complete @Qualifier
annotations tutorial is covered in Qualifying The Right Bean using @Qualifier tutorial.
@Required :
Sometimes it is required to ensure that the bean property is populated at configuration time through an explicit property value in a bean definition or through autowiring, Spring allows enforcing this using @Required
annotation on the bean property's setter methods.
Complete @Required
annotations tutorial is covered in @Required Annotation in Spring tutorial.
@Value:
Spring’s @Value
annotation is used to load values from a Java properties file. This could look like this:
@Service public class MyService { @Value("${my.config.property.key}") private String someConfigValue; //
In the above code, Spring would inject the value for the key my.config.property.key from your properties file right into your class.
Complete @Value
annotations tutorial is covered in Spring : How To Load Properties File using @Value Annotation tutorial.
@Scope:
Instead of defining your bean scope in xml, you can also annotate your bean using the @Scope Annotation in Spring
annotation. This annotation takes a name parameter indicating which bean scope to use.
Complete @Scope
annotations tutorial is covered in Spring Bean Scopes and Lifecycle tutorial.
@Transactional:
@Transactional
annotation is used to define a particular method that should be within a transaction.
Complete @Transactional
annotations tutorial is covered in Configuring Transaction Using Annotations in Spring Framework tutorial.
Configure your transactions with @Transactional
spring annotation.
@Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeDAO employeeDAO; @Transactional public Employee findByName(String name) { Employee employee = employeeDAO.findByName(name); return employee; } ... }
@RestController:
@RestController
annotation is inherited from the @Controller
annotation. This annotation is the special version of @Controller
annotation for implementing the RESTful Web Services. @RestController
has been added as part of the Spring 4 release.
Spring MVC Annotations
@Controller
In Spring MVC we need to annotate our controller classes with@Controller
annotation.
@Controller public class EmployeeController { ... }
@RequestMapping
You can use @RequestMapping
annotation to map URLs to 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; ... }
@PathVariable
You can use the @PathVariable
annotation on a method argument to bind it to the value of a URI template variable.
@RequestParam
You can bind request parameters to method variables using @RequestParam
annotation.
@ModelAttribute
@ModelAttribute
annotation can be used as the method arguments or before the method declaration. The primary objective of this annotation to bind the request parameters or form fields to an model object.
Related Articles