Self injection with Spring

By the way, the more elegant solution to the self-invocation problem is to use AspectJ Load-Time Weaving for your transactional proxies (or whatever AOP-introduced proxy you're using).

For example, with annotation-driven transaction management, you can use the "aspectj" mode as follows:

<tx:annotation-driven mode="aspectj" />

Note that the default mode is "proxy" (i.e., JDK dynamic proxies).

Regards,

Sam


Update: February 2016

Self autowiring will be officially supported in Spring Framework 4.3. The implementation can be seen in this GitHub commit.


The definitive reason that you cannot autowire yourself is that the implementation of Spring's DefaultListableBeanFactory.findAutowireCandidates(String, Class, DependencyDescriptor) method explicitly excludes the possibility. This is visible in the following code excerpt from this method:

for (String candidateName : candidateNames) {
    if (!candidateName.equals(beanName) && isAutowireCandidate(candidateName, descriptor)) {
        result.put(candidateName, getBean(candidateName));
    }
}

FYI: 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 in fact equals the beanName). Thus you simply cannot autowire a bean with itself (at least not as of Spring 3.1 M1).

Now as for whether or not this is intended behavior semantically speaking, that's another question. ;)

I'll ask Juergen and see what he has to say.

Regards,

Sam (Core Spring Committer)

p.s. I've opened a Spring JIRA issue to consider supporting self-autowiring by type using @Autowired. Feel free to watch or vote for this issue here: https://jira.springsource.org/browse/SPR-8450


This code works too:

@Service
public class UserService implements Service {

    @Autowired
    private ApplicationContext applicationContext;

    private Service self;

    @PostConstruct
    private void init() {
        self = applicationContext.getBean(UserService.class);
    }
}

I don't know why, but it seems that Spring can get the bean from ApplicationContext if is created, but not initialized. @Autowired works before initialization and it cannot find the same bean. So, @Resource maybe works after @Autowired and before @PostConstruct.

But I don't know, just speculating. Anyway, good question.


Given above code I don't see a cyclic dependency. You injecting some instance of Service into UserService. The implementation of the injected Service does not necessarily need to be another UserService so there is no cyclic dependency.

I do not see why you would inject a UserService into UserService but I'm hoping this is a theoretic try out or such.