Spring annotations @Repository and @Service

Spring

Spring Problem Overview


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?

Spring Solutions


Solution 1 - Spring

There are a few reasons:

  1. It's easier to target pointcuts with more specific annotations. Do not underestimate the usefulness of this!
  2. The @Repository annotation carries with it some additional functionality: it causes exceptions to be wrapped up as DataAccessExceptions.
  3. The @Service annotation may gain additional semantics in the future but it's not happened yet…

Solution 2 - Spring

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).

Solution 3 - Spring

I believe that there are two things Spring had in mind when they added these Component annotations.

  1. They can be used to specify point cuts across all objects annotated with that sub-component. (All @Repository or all @Service pointcuts)
  2. I think Spring also mentioned that they would be adding some future functionality to them. (I have no citation for this, I just think I read this somewhere)

Solution 4 - Spring

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").

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlueSkyView Question on Stackoverflow
Solution 1 - SpringDonal FellowsView Answer on Stackoverflow
Solution 2 - SpringLuciano FiandesioView Answer on Stackoverflow
Solution 3 - Springnicholas.hauschildView Answer on Stackoverflow
Solution 4 - SpringlrkwzView Answer on Stackoverflow