@Resource vs @Autowired
In spring pre-3.0 it doesn't matter which one.
In spring 3.0 there's support for the standard (JSR-330) annotation @javax.inject.Inject
- use it, with a combination of @Qualifier
. Note that spring now also supports the @javax.inject.Qualifier
meta-annotation:
@Qualifier
@Retention(RUNTIME)
public @interface YourQualifier {}
So you can have
<bean class="com.pkg.SomeBean">
<qualifier type="YourQualifier"/>
</bean>
or
@YourQualifier
@Component
public class SomeBean implements Foo { .. }
And then:
@Inject @YourQualifier private Foo foo;
This makes less use of String-names, which can be misspelled and are harder to maintain.
As for the original question: both, without specifying any attributes of the annotation, perform injection by type. The difference is:
@Resource
allows you to specify a name of the injected bean@Autowired
allows you to mark it as non-mandatory.
Difference in @Resource and @Autowired
@Autowired in combination with @Qualifier also autowires by name. The main difference is is that @Autowired is a spring annotation whereas @Resource is specified by the JSR-250. So the latter is part of normal java where as @Autowired is only available by spring.
if you intend to express annotation-driven injection by name, do not
primarily use @Autowired - even if is technically capable of referring
to a bean name through @Qualifier values. Instead, prefer the JSR-250
@Resource annotation which is semantically defined to identify a
specific target component by its unique name, with the declared type
being irrelevant for the matching process.As a specific consequence of this semantic difference, beans which are
themselves defined as a collection or map type cannot be injected via
@Autowired since type matching is not properly applicable to them. Use
@Resource for such beans, referring to the specific collection/map
bean by unique name.
Note: In contrast to @Autowired which is applicable to fields, constructors and multi-argument methods (allowing for narrowing through qualifier annotations at the parameter level), @Resource is only supported for fields and bean property setter methods with a single argument. As a consequence, stick with qualifiers if your injection target is a constructor or a multi-argument method.
Difference between @Qualifier and @Resource
@Autowired
can be used alone . If it is used alone , it will be wired by type . So problems arises if more than one bean of the same type are declared in the container as @Autowired
does not know which beans to use to inject. As a result , use @Qualifier
together with @Autowired
to clarify which beans to be actually wired by specifying the bean name (wired by name)
@Resource
is wired by name too . So if @Autowired
is used together with @Qualifier
, it is the same as the @Resource
.
The difference are that @Autowired
and @Qualifier
are the spring annotation while @Resource
is the standard java annotation (from JSR-250) . Besides , @Resource
only supports for fields and setter injection while @Autowired
supports fields , setter ,constructors and multi-argument methods injection.
It is suggested to use @Resource
for fields and setter injection. Stick with @Qualifier
and @Autowired
for constructor or a multi-argument method injection.
See this:
If you intend to express annotation-driven injection by name, do not
primarily use @Autowired - even if is technically capable of referring
to a bean name through @Qualifier values. Instead, prefer the JSR-250
@Resource annotation which is semantically defined to identify a
specific target component by its unique name, with the declared type
being irrelevant for the matching process.
Inject and Resource and Autowired annotations
The difference between @Inject vs. @Autowire vs. @Resource?
@Autowired: spring propriety annotation (as opposed to @Inject and @Resource) that inject a resource by-type, i.e. by the class of by the interface of the annotated field or contractor. In case we have few implementation of an interface or a subclass we can narrow down the selection using the @Qualifier annotation to avoid ambiguity. For a fallback match, the bean name is considered a default qualifier value. Although you can use this convention to refer to specific beans by name, @Autowired is fundamentally about type-driven injection with optional semantic qualifiers.
@Inject: Annotation based on JSR-330 (Dependency Injection for Java) identifies injectable constructors, methods, and fields. This annotation is an almost complete drop-in replacement for Spring’s @Autowired annotation. So, instead of using the Spring-specific @Autowired annotation, you might choose to use @Inject. One of the differences between @Autowired and @Inject is that @Inject does not have the required field so in case we fail to find a suitable object to inject it will fail while @Autowired can used required=false and allow null able field (only if required!).
Advantage of @Inject annotation is that rather than inject a reference directly, you could ask @Inject to inject a Provider. The Provider interface enables, among other things, lazy injection of bean references and injection of multiple instances of a bean.
In case we have few implementation of an interface or a subclass we can narrow down the selection using the @Named annotation to avoid ambiguity. @Named annotation works much like Spring’s @Qualifier
@Resource: annotation based on JSR-250. @Resource is quite similar to @Autowired and @Inject, but the main difference is the execution paths taken to find out the required bean to inject. @Resource will narrow down the search first by name then by type and finally by Qualifiers (ignored if match is found by name). @Autowired and @Inject will narrow down the search first by type then by qualifier and finally by the name.
Meaning of @Resource annotation
First of all, to understand the point of @Resource
you need to understand the Inversion of Control (IoC).
Inversion of Control is a principle in software development which goes that the control of objects should be transferred to a container or a framework.
Dependency Injection (DI) is a pattern of IoC implementation, where the control being inverted is the setting of object’s dependencies.
The act of composing objects with other objects (injecting) is done by a container rather than by the objects themselves.
Using a DI framework (like Spring IoC
or EJB
) you're creating your POJOs and configuring the framework (a POJO configured such way called a Bean
). A Bean
may have different scopes, like singleton (1 object instance per container), prototype (creates a new instance of an object per injection or explicit call) and etc.
So far, so good. What's next? It's time to use our beans.
@Resource
is the annotation that will help to extract beans from the container.
There are several lookup options to extract beans:
- Match by Name
- Match by Type
- Match by Qualifier
Using @Resource
without any parameters will trigger Match by Type lookup type.
There is an example of usage or @Resource
with field injection and Spring framework with Java-based configuration and Match by Name:
@Configuration
public class ApplicationContext {
// Put the bean into the spring container
@Bean(name = "userFile")
public File userFile() {
File file = new File("user.txt");
return file;
}
}
@Service
class UserService {
// Ask the container to get the bean and 'put' it here (inject)
@Resource(name = "userFile")
private File userFile;
}
@Resource
is usually used to inject data sources, singleton services, context configurations and etc.
Spring, @Autowired, @Resource and property
@Autowired
, @Resource
and @Inject
I think the part of the Spring Reference that you need to read is
3.9 Annotation-based container configuration
There are many sets of similar annotations. Often, there is a Spring and a non-Spring version that do the same thing. Spring tries to embrace standards whenever they are available, but often the Spring guys came up with their own ideas before a standard appeared. Example: Spring supports its own @Autowired
annotation, but also the new @Inject
annotation from JSR-330, as well as the JSR-250 @Resource
annotation (all of which can be used to do the same thing).
The key concept here is that Spring doesn't force you to use its own code, but supports many different ways without coupling your application to Spring. (There are still a few annotations that have no non-Spring equivalent, like @Transactional
, but if you want to, you can add that functionality via XML instead, so you can keep your application 100% Spring free and still use many convenience annotations and of course Spring wiring and lifecycle management behind the scenes.
Related Topics
How to Retrieve Element Value of Xml Using Java
How to Create an .Exe for a Java Program
Java:If a Extends B and B Extends Object, Is That Multiple Inheritance
How to Create a Jandex Index in Quarkus for Classes in a External Module
Interview Question: Check If One String Is a Rotation of Other String
What Is More Efficient, I++ or ++I
Proper Implementation of Cubic Spline Interpolation
Pure Java HTML Viewer/Renderer for Use in a Scrollable Pane
How to Escape Special HTML Characters in Jsp
Java Unsupported Major Minor Version 52.0
Loading Images from Jars for Swing HTML
Why One Should Prefer Using CSS Over Xpath in Ie
Javafx Tableview Text Alignment
Spring Boot CSS Showing Up Blank/Not Loading After Trying Everything
Resume Http File Download in Java
Android.View.Inflateexception Error Inflating Class Android.Webkit.Webview