Description
Sam Brannen opened SPR-8450 and commented
Background
Autowiring a bean with an instance of itself is not something one would normally do, but there are cases where it might be useful -- for example, to route method calls through the proxy that wraps the bean. There are of course alternatives to this, such as using load-time weaving with AspectJ proxies instead of JDK dynamic proxies.
Note that self-autowiring by name via @Resource
is permitted by the framework; whereas, self-autowiring by type is not permitted by the framework as can be seen in the following code snippet from DefaultListableBeanFactory
's findAutowireCandidates(String, Class, DependencyDescriptor)
method.
for (String candidateName : candidateNames) {
if (!candidateName.equals(beanName) && isAutowireCandidate(candidateName, descriptor)) {
result.put(candidateName, getBean(candidateName));
}
}
The name of the bean (i.e., the bean that's trying to autowire itself) is beanName
. That bean is in fact an autowire candidate, but the above if-condition returns false
(since candidateName
equals the beanName
). Thus you simply cannot autowire a bean with itself by type (at least not as of Spring 3.1 M2).
Goal
Add support for self-autowiring using @Autowired
on fields and methods.
Stack Overflow Discussion
This topic was brought to our attention via a discussion on Stack Overflow.
Affects: 3.0.5
Issue Links:
- Self autowiring does not work for transactional beans [SPR-16645] #21186 Self autowiring does not work for transactional beans
- Self reference fallback in 4.3 is not meant to apply to collection elements [SPR-14965] #19532 Self reference fallback in 4.3 is not meant to apply to collection elements
- @Autowired does not work for target bean of type Collection [SPR-12180] #16794
@Autowired
does not work for target bean of type Collection - Define and document rules for @Autowired self-injection in case of ambiguity [SPR-14402] #18973 Define and document rules for
@Autowired
self-injection in case of ambiguity
18 votes, 23 watchers