overview
In Spring dependency injection, everyone knows @Resource and @Autowired. Obviously @Resource supports both name and type, so why @Autowired?
source of both
@Resource
Released with JSR 250 on May 11, 2006 : similar to a definition, it can be freely implemented by other frameworks or components, and is not strongly bound to spring
@Autowired
Released with Spring 2.5 on November 19, 2007 : This is the son of Spring
Why does Spring support two annotations with similar functions at the same time?
-
Their concepts are different, @Resource tends to find known resources, while Autowired tends to try to search for resources by type.
-
To facilitate the migration of other frameworks, @Resource is a specification, as long as other frameworks conform to the JSR-250 specification, Spring is compatible.
Since @Resource is more inclined to find known resources, why does it also have the function of injecting by type?
Guess: It may be for compatibility switching from Spring to other frameworks. Other frameworks do not necessarily have annotations like @AutoWired injected by type.
scenes to be used
@Resource tends to be a deterministic single resource, and @Autowired is a type to match all resources that match this type.
Such as collection injection, @Resource is also possible, but it is recommended to use @Autowired. It is not recommended to use @Resource to inject collection resources. In essence, collection injection is not single and uncertain.