the_way
the_way

Reputation: 181

Difference in @Resource and @Autowired

I don't understand why the following line gives an error when i annotate it with @Resource, I don't get this error when i write @Autowired.

@Resource(name = "systemConfigService")
private SystemConfigService systemConfigService;

It tells , unable to resolve bean systemConfigService

SystemConfigService is an interface.

Upvotes: 2

Views: 10624

Answers (1)

0gam
0gam

Reputation: 1423

@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.

Upvotes: 3

Related Questions