Reputation: 1453
What are the advantages of using @Repository and @Service?
Don't tell me about component scanning etc., I am looking forward to something extra benefits or features that are there if at all.
what happens if I don't use it? what is that I would be missing?
Upvotes: 72
Views: 46577
Reputation: 137577
There are a few reasons:
@Repository
annotation carries with it some additional functionality: it causes exceptions to be wrapped up as DataAccessException
s.@Service
annotation may gain additional semantics in the future but it's not happened yet…Upvotes: 73
Reputation: 6513
If you TDD it would be useful to carefully design (an test of course) @Services because they will benefit of full injection of all the @Autowired components you have defined.
You could implement your functionalities directly into a @Controller for example, but in this case testing will be harder and you need to define all the mock elements (quite easier in springframework 3.1 but still "bad design").
Upvotes: 3
Reputation: 10205
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).
Upvotes: 65
Reputation: 42849
I believe that there are two things Spring had in mind when they added these Component annotations.
Upvotes: 5