Uploaded image for project: 'Spring Framework'
  1. Spring Framework
  2. SPR-8450

Support @Autowired-like self injection

    XMLWordPrintable

    Details

    • Type: New Feature
    • Status: Closed
    • Priority: Major
    • Resolution: Complete
    • Affects Version/s: 3.0.5
    • Fix Version/s: 4.3 RC1
    • Component/s: Core
    • Labels:
      None
    • Last commented by a User:
      true

      Description

      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.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              juergen.hoeller Juergen Hoeller
              Reporter:
              sbrannen Sam Brannen
              Last updater:
              Spring Issues Spring Issues
              Votes:
              18 Vote for this issue
              Watchers:
              23 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved:
                Days since last comment:
                3 years, 37 weeks, 4 days ago