Tuesday, December 20, 2011

Spring annotations - @Service and @Repository

In Spring 2.0 and later, the @Repository annotation is a marker for any class that fulfills the role or stereotype (also known as Data Access Object or DAO) of a repository. Among the uses of this marker is the automatic translation of exceptions.

@Service serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning. What this means is that you could annotate your service-layer classes with @Component, but by annotating them with @Service instead, your classes are more properly suited for processing by tools or associating with aspects, since @Service makes an ideal target for pointcuts.

@Service
public class WorldServiceImpl implements WorldService {
@Autowired
private CountryDao countryDao;
...
}
@Service - business service facade (it makes use of DAO)
@Repository - indicate that a class function as a repository or a data access object (DAO)

http://www.slideshare.net/kensipe/spring-3-annotated-development

The @Repository annotation (introduced in Spring 2.0) and @Service annotation (introduced in Spring 2.5) are specialization of the @Component annotation.
The main advantage of using @Repository or @Service over @Component is that it's easy to write an AOP pointcut that targets, for instance, all classes annotated with @Repository.
Also, the specialized annotations help to clearly demarcate application layers (in a standard 3 tiers application).
http://stackoverflow.com/questions/6256331/spring-annotations-repository-and-service

Then the only thing you need in the xml is the context:component-scan tag to tell Spring which package to scan for @Component annotations. @Repository extends @Component so @Repository is an @Component.
http://www.coderanch.com/t/61389/oa/autowired-annotation


No comments: