Compare and contrast Spring's `@Autowired` annotation with the standard Java `@Resource` annotation for dependency injection.

Java interview question for Advanced practice.

Answer

@Autowired and @Resource are both annotations used for dependency injection, but they have different origins and default behaviors. @Autowired (Spring-specific): Matching Strategy: Its primary matching strategy is by type. It looks for a bean in the context that matches the type of the injection point. Ambiguity Resolution: If multiple beans of the same type exist, it will fall back to matching by name (matching the bean's ID to the field or parameter name). If ambiguity still exists, it throws a NoUniqueBeanDefinitionException. This ambiguity must be resolved with @Qualifier or @Primary. Required by Default: By default, it considers the dependency to be mandatory. If no matching bean is found, it throws an exception. This can be changed with @Autowired(required = false). @Resource (Java Standard - JSR-250): Matching Strategy: Its default matching strategy is by name. It first looks for a bean with a name that matches the field or parameter name. Ambiguity Resolution: If no match is found by name, it will fall back to matching by type. If there are still multiple matching candidates by type, it will throw an exception. The name attribute (e.g., @Resource(name = "mySpecificBean")) provides explicit control. Origin: It is part of the standard Java library (javax.annotation.Resource or jakarta.annotation.Resource), making it framework-agnostic. Key Difference: The main difference is the order of matching: @Autowired is type-first, while @Resource is name-first.

Explanation

The @Resource annotation was defined in JSR-250, a Java Specification Request for common annotations, making it a more portable choice between different dependency injection frameworks.

Related Questions