Skip to content

Support @Autowired-like self injection [SPR-8450] #13096

Closed
@spring-projects-issues

Description

@spring-projects-issues

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:

18 votes, 23 watchers

Metadata

Metadata

Assignees

Labels

has: votes-jiraIssues migrated from JIRA with more than 10 votes at the time of importin: coreIssues in core modules (aop, beans, core, context, expression)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions