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?
@Component is a generic stereotype for any Spring-managed component. @Service annotates classes at the service layer. @Repository annotates classes at the persistence layer, which will act as a database repository.
@Component is a generic stereotype for any Spring-managed component or bean. @Repository is a stereotype for the persistence layer. @Service is a stereotype for the service layer. @Controller is a stereotype for the presentation layer (spring-MVC).
There are some important implications we should note because of the differences between @Component and @Bean. @Component is a class-level annotation, but @Bean is at the method level, so @Component is only an option when a class's source code is editable. @Bean can always be used, but it's more verbose.
@Controller annotation indicates that a particular class serves the role of a controller. @Service Annotation is a specialization of @Component Annotation. @Repository Annotation is also a specialization of @Component Annotation. @Controller annotation is also a specialization of @Component annotation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With