We are going to discuss about spring mvc annotations. And how to use spring annotations. It’s from Spring 2.5 that allowed us to configure dependency injection using spring annotations. Instead of wiring bean’s in XML file, we do bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.
Wiring of beans using annotations is not on by default, we need to enable it in configuration file. Your spring configuration file will be something like :
Now I am going to explain some of the most used spring annotations.
@Component: It’s a generic stereotype for any Spring-managed component.
@Controllerare specializations of
@Componentfor more specific use cases, for example, in the persistence, service, and presentation layers, respectively.
@Controller: Controller annotation is used to denote that the class is controller. It contains method which serve the http requests, request mappings are done at method level or class level.
@Service: Annotate all your service classes with
@Service. All your business logic will be in Service classes. Controller and DAO layers will not have any business logic in there.
@Repository: Annotate all your DAO classes with
@Repository. All your database access logic should be in DAO classes.
@Autowire: Spring beans are injected or acquired using autowire annotation.
@Qualifier("bean name"): Qualifier annotation is used along with autowire. It is used as an discriminator.
@Valueannotation is used to get the value of key mentioned/mapped in properties file.
There are some simple reasons to explain why should we use’em :
- The main advantage of using
@Componentis that it’s easy to write an AOP pointcut that targets, for instance, all classes annotated with
- You don’t have to write bean definitions in context xml file. Instead annotate classes and use those by autowiring.
- Specialized annotations help to clearly demarcate application layers (in a standard 3 tiers application).
Now, Practically performance impact of using context xml beans & annotations is the same. Component scanning is a bit more expensive (when you scan for
@Component). The annotations are ‘parsed’ with reflection, the xml – with an xml parser.
Here are some examples of how we use annotations :
At Controller level :
At service level we autowire dao beans and invoke dao methods.
And at the DAO layer, we fetch data from database using underlying ORM and return it to service class.
See how we are using annotations in application. Visit my github repo for this code.