Understanding Spring’s @Autowired vs @Resource: Usage, Differences, and Implementation Details
This article compares Spring's @Autowired and @Resource annotations, explains their injection semantics, outlines practical differences, and dives into the internal implementation classes and processing steps that Spring uses to resolve and inject beans.
1. Background
Both @Resource and @Autowired are used for bean injection in Spring and are frequently used in everyday development. The author prefers @Resource because IDEA shows warning highlights for @Autowired field injection, although the warnings are not actual errors.
Field injection is not recommended
The Spring team discourages field injection and recommends constructor‑based injection.
IDEA may also report "cannot find bean type" warnings, but the beans are correctly injected when the application starts.
Therefore the author chooses @Resource to avoid the IDE warnings, while noting that @Autowired itself works fine and the warnings are an IDE issue.
2. Overview
Spring supports the @Autowired and @Resource annotations for dependency injection.
2.1 @Autowired definition
@Autowiredis provided by Spring and must be imported from org.springframework.beans.factory.annotation.Autowired. The source definition is:
<span style="color: #5c6370; font-style: italic; line-height: 26px">/**
* @since 2.5
* @see AutowiredAnnotationBeanPostProcessor
* @see Qualifier
* @see Value
*/</span>
<span style="color: #61aeee; line-height: 26px">@Target</span>({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
<span style="color: #61aeee; line-height: 26px">@Retention</span>(RetentionPolicy.RUNTIME)
<span style="color: #61aeee; line-height: 26px">@Documented</span>
<span style="color: #c678dd; line-height: 26px">public</span> <span style="color: #61aeee; line-height: 26px">@interface</span> Autowired {
<span style="color: #5c6370; font-style: italic; line-height: 26px">/**
* Declares whether the annotated dependency is required.
* <p>Defaults to {@code true}.</p>
*/</span>
<span style="color: #c678dd; line-height: 26px">boolean</span> required() default true;
}Injection resolution steps:
1) Match a bean by type in the context.
2) If multiple beans match, match by name (or by @Qualifier if present).
3) If still ambiguous, fall back to the variable name.
4) If no bean is found, injection fails unless @Autowired(required=false) is used.
2.2 @Resource definition
@Resourceis a JDK 1.6 annotation provided by JSR‑250 and must be imported from javax.annotation.Resource. Its source definition is:
<span style="color: #61aeee; line-height: 26px">@Target</span>({TYPE, FIELD, METHOD})
<span style="color: #61aeee; line-height: 26px">@Retention</span>(RUNTIME)
<span style="color: #c678dd; line-height: 26px">public</span> <span style="color: #61aeee; line-height: 26px">@interface</span> Resource {
String name() default "";
String lookup() default "";
Class<?> type() default java.lang.Object.class;
enum AuthenticationType { CONTAINER, APPLICATION }
AuthenticationType authenticationType() default AuthenticationType.CONTAINER;
boolean shareable() default true;
String mappedName() default "";
String description() default "";
}Default injection is by name; the name attribute maps to the bean name, and the type attribute maps to the bean type. If name is omitted, the field name is used for name‑based lookup. When a name match fails, Spring falls back to type‑based injection.
2.2 Differences between @Autowired and @Resource
Dependency identification : @Autowired defaults to byType (name can be forced with @Qualifier); @Resource defaults to byName and falls back to byType.
Applicable targets : @Autowired can be placed on constructors, methods, parameters, fields, and annotation types; @Resource can be placed only on methods and fields.
Provider : @Autowired is Spring‑specific; @Resource is defined by JSR‑250.
3. Implementation Principles
3.1 @Autowired implementation
Spring resolves @Autowired via AutowiredAnnotationBeanPostProcessor, which extends InstantiationAwareBeanPostProcessorAdapter and implements MergedBeanDefinitionPostProcessor, PriorityOrdered, and BeanFactoryAware. This processor is invoked during bean creation in DefaultListableBeanFactory → AbstractAutowireCapableBeanFactory → createBean → doCreateBean.
public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {
/**
* Create a new {@code AutowiredAnnotationBeanPostProcessor} for Spring's
* standard {@link Autowired} and {@link Value} annotations.
* <p>Also supports JSR-330's {@link javax.inject.Inject} annotation,
* if available.
*/
@SuppressWarnings("unchecked")
public AutowiredAnnotationBeanPostProcessor() {
this.autowiredAnnotationTypes.add(Autowired.class);
this.autowiredAnnotationTypes.add(Value.class);
try {
this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
ClassUtils.forName("javax.inject.Inject", AutowiredAnnotationBeanPostProcessor.class.getClassLoader()));
logger.trace("JSR-330 'javax.inject.Inject' annotation found and supported for autowiring");
} catch (ClassNotFoundException ex) {
// JSR-330 API not available - simply skip.
}
}
...
}Key processing methods: postProcessMergedBeanDefinition merges bean definitions and builds injection metadata. findAutowiringMetadata retrieves or builds InjectionMetadata for a given class. buildAutowiringMetadata scans fields and methods for @Autowired (and @Value) annotations, creating InjectedElement instances. postProcessPropertyValues (or postProcessProperties) obtains the metadata and performs the actual injection via metadata.inject(...).
The injection flow ultimately calls populateBean, which invokes the post‑processor to set field values or invoke setter methods.
3.2 @Resource implementation
@Resourceis processed by CommonAnnotationBeanPostProcessor. Its overall flow mirrors that of @Autowired: the post‑processor participates in bean creation, discovers injection points, builds metadata, and injects the resolved bean. The article notes the similarity and does not repeat the full source code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Shepherd Advanced Notes
Dedicated to sharing advanced Java technical insights, daily work snippets, and the power of persistent effort.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
