When moving to Spring 2.5.x I found that it adds more stereotype annotations (on top of @Repository from 2.0): @Component, @Service and @Controller. How do you use them? Do you rely on implicit Spring support or you define custom stereotype specific functions/aspects/features? Or is it predominately for marking beans (compile time, conceptual, etc.)?
Share
The following stereotype annotations in 2.5 can be used in a Spring MVC application as an alternative to wiring the beans in XML:
@Repository – for DAO beans – allows
you to throw DataAccessException when
the data source is not available.
@Service – for business beans –
are fairly simple beans that have some
default retention policies set up.
@Controller – for servlets –
allows you to set up page request
mappings, etc.
In addition, a generic fourth annotation has been introduced: @Component. All of the MVC annotations are specialisations of this one, and you can even use @Component on it’s own, though by doing this in Spring MVC, you will not make use of any future optimisations/functionality added to the higher-level annotations. You can also extend @Component to create your own custom stereotypes.
Here is a quick example of the MVC annotations in action… First, the data access object:
The service:
And finally, the controller:
I found this article very good for giving a broad overview of the stereotype annotations, in addition to the official documentation.