Self injection with Spring

44,584

Solution 1

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

Solution 2

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.

Solution 3

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

Solution 4

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.

Solution 5

Get AOP proxy from the object itself question suggests alternative hacky approach with AopContext.currentProxy() that may be suitable for special cases.

Share:
44,584
Premraj
Author by

Premraj

Software developer mainly working with Java.

Updated on July 05, 2022

Comments

  • Premraj
    Premraj almost 2 years

    I tried the following code with Spring 3.x which failed with BeanNotFoundException and it should according to the answers of a question which I asked before - Can I inject same class using Spring?

    @Service
    public class UserService implements Service{
        @Autowired
        private Service self;
    }
    

    Since I was trying this with Java 6, I found the following code works fine:

    @Service(value = "someService")
    public class UserService implements Service{
        @Resource(name = "someService")
        private Service self;
    }
    

    but I don't understand how it resolves the cyclic dependency.

    EDIT:
    Here's the error message. The OP mentioned it in a comment on one of the answers:

    Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.spring.service.Service] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

  • Premraj
    Premraj about 13 years
    I have only One implementation of Service and thats UserService :).. Same code fails with Spring @Autowired but works with @Resource
  • Premraj
    Premraj about 13 years
    Can aspectj work with JDK proxies? I guess it needs CGLib right?
  • Andy Dufresne
    Andy Dufresne almost 13 years
    This explains why @Autowired does not work but doesn't explain how and why @Resource works. Anyone?
  • Premraj
    Premraj almost 13 years
    @Amit - this does explain!! they are only excluding autowired candidates and not checking for other ones like @Resource and etc.
  • Shamu
    Shamu about 12 years
    Wiring a bean into itself could be useful if the service uses a spring cache proxy around it and you want the internal calls to benefit from this cache.
  • karlita94
    karlita94 about 11 years
    I think something like this can be very usefull on certain occasions, e.g. there are times when you need to have a method been wraped by a transactional proxy (espesially with requires_new) which may be self-invoked. Having to "separate" such functionality often leads to antipatterns and poor design in genertal
  • karlita94
    karlita94 about 11 years
    Well aspectj deals with self-invocation but creates other problems, also last time i checked it is not recommended SpringSource docs.
  • Erwin Raets
    Erwin Raets almost 11 years
    Agree with nvrs, same-class @Transactional proxying is what led me here. "Use AspectJ instead of CGLib" isn't a useful answer when you have a mature codebase. Using @Resource will probably solve my problem but @Autowired would be preferable as that is our standard.
  • Andrii Andriichuk
    Andrii Andriichuk over 8 years
    Cool, injecting context into your application bean. It's best practice ever!
  • sinuhepop
    sinuhepop over 8 years
    @avrilfanomar: Well, if a class needs to be conscious that there is a proxy of itself you are breaking DI abstraction anyway, so I think that accessing your container is not much worse.
  • Andrii Andriichuk
    Andrii Andriichuk over 8 years
    Why does it break DI? I see no evil in injecting self e.g. for using transactional method as it should be.
  • Xiangyu
    Xiangyu almost 8 years
    Just for anyone who's waiting for Spring 4.3. I'm now using it. But self-reference only get more exception description, and is still not allowed, at least by default set-up.
  • Sam Brannen
    Sam Brannen almost 8 years
    @Xiangyu, that's not true. Self injection via @Autowired works fine with Spring Framework 4.3 as long as there is a single candidate bean of the autowired type. And... if there is more than one such candidate, @Qualifier can be used to disambiguate. I just verified this.
  • Xiangyu
    Xiangyu almost 8 years
    @SamBrannen In my case there is bean inheritance, so I believe it is possible that self injection is rejected because of more than one candidate.
  • Sam Brannen
    Sam Brannen almost 8 years
    @Xiangyu, Juergen Hoeller just documented this three days ago: github.com/spring-projects/spring-framework/commit/…
  • OrangeDog
    OrangeDog about 7 years
    Remember to add @Lazy
  • ssbh
    ssbh over 3 years
    I tried same thing above with more fields in UserService class. but when I do self.morefield.xxx. it throws NPE
  • T Tse
    T Tse almost 3 years
    Not sure if sarcasm or not, @AndriiAndriichuk. Users stumbling upon this question (like, me) usually aren't too well-versed in best practices.
  • Andrii Andriichuk
    Andrii Andriichuk almost 3 years
    @TTse Injecting application context into service bean (which is not related to spring customization) is a wrong approach.
  • ennth
    ennth over 2 years
    @sinuhepop Damn, I have the same setup Class implementing Interface), but no matter what I do, I get a NullPointerException when I try to call a method on the "self" variable
  • ennth
    ennth over 2 years
    tried everything , could not get this to work. Not sure if its because I have a concrete class implementing an Interface in another module (multi-module maven project) and I also have the data types for some of the Methods in my class generated by the SwaggerCodeGenPlugin
  • Gilson
    Gilson over 2 years
    Without known what you build is hard to guess what is happening on your side. Also, this code above, from 3 years ago, is something that I would avoid today. If you seems to needs self injection, probably you have an architect problem. You can separate things where each concept belongs to its own class and then you will no need to self inject anymore.