简体   繁体   中英

What's the difference between how @Component and @Repository / @Service annotations are processed?

I've stumbled upon a rather strange issue today with Spring 3.0:

There's an abstract class A and its concrete implementation A_Impl . A_Impl is annotated as @Repository and is auto-scanned by Spring ( <context:component-scan> and <context:annotation-config/> are both declared in context). A and A_Impl are deployed in separate JARs (not sure if that matters). Everything works just fine.

Now, I was reviewing that code and @Repository didn't seem like a good fit semantically (the class in question has nothing to do with persistence) so - in my infinite wisdom - I've decided to change that to more generic @Component . Needless to say, everything blew up leaving me looking like a complete idiot. The error (which occurred during Spring context initialization) was Spring's ClassPathResource.getInputStream() method complaining about A class not being there (it is, I've manually checked; plus regular class loader finds it just fine)

Nothing else has changed . If I swap @Component for @Repository context initializes, if I swap them back it doesn't with the above error. Spring documentation claims there's no difference between @Component and @Repository which is clearly a damned lie :-) So I wonder - what is the difference?

I've been using @Component without troubles.

The only thing (although not-so-intelligent one) that comes to my mind as possibility is that your @Component might not be the spring one. Tapestry, for example, has an annotation named the same way. Other frameworks may also have it. So check your imports.

|Annotation  | Meaning                                             |
+------------+-----------------------------------------------------+
| @Component | generic stereotype for any Spring-managed component |
| @Repository| stereotype for persistence layer                    |
| @Service   | stereotype for service layer                        |
| @Controller| stereotype for presentation layer (spring-mvc)      |

Use of @Service and @Repository annotations are important from database connection perspective.

  1. Use @Service for all your web service type of DB connections
  2. Use @Repository for all your stored proc DB connections

If you do not use the proper annotations, you may face commit exceptions overridden by rollback transactions. You will see exceptions during stress load test that is related to roll back JDBC transactions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM