This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I had a horrible day by searching for the difference betweeen @Resource and @Component.
I know how it works if we use @Resource at field-level and method-level. But, how to use @Resource at class-level. Is it similar to @Component.
@Component is the root stereo type annotation. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning. The JSR 330 annotation that is more of a drop in replacement for this is the @Named annotation.
Since most projects I am on are unlikely to ever operate without Spring I prefer to use the subclasses of @Component as they more specifically define the behavior of the class and in some cases (such as @Repository) add additional behavior. There are lots of annotations that extend Component some examples are @Service, @Repository, @MessageEndpoint etc.
The blog you mentioned for @Resource explained only about field level and method level injections. But I desperately need an example on how to use @Resource at class level. That is what my major concern.
Spring also supports injection using the JSR-250 @Resource annotation on fields or bean property setter methods.
This implies that Spring only supports this annotation on fields or setters. Like I said I prefer to use the Spring annotations since the applications I work on will always be using Spring. If you have a really odd scenario where that is not the case or you just really want to use an JSR annotation instead than use @Named instead of @Component as was described in a link in my previous post.
Note the @Resource annotation is also useful for wiring in collections that are defined as @Bean's
Yup and those links have nothing at all to do with Spring. My impression from your original question was you were asking about using @Resource inside a Spring application and you were trying to draw comparisons between @Resource and @Component. As far that question is concerned I think my previous posts addressed it.
Now you are moving out of the realm of Spring and into EJB 3.1. @Resource of course is not a Spring annotation but Spring does support its usage in its own way. Without Spring this annotation would be used in a full JEE container and the class that is annotated would be managed by the container. In this case if the @Resource is applied at the class level a name must be specified and that would result in a JNDI (environment) look-up for the resource. See the java doc here: