1. Overview

Self-injection means that a Spring bean injects itself as a dependency. It uses the Spring container to obtain a reference to itself and then uses that reference to perform some operation.

In this short tutorial, we’ll see how to use self-injection in Spring.

2. Use Case for Self-Injection

The most common use case for self-injection is to bypass Spring AOP limitations when it’s necessary to apply an aspect to a method or class that is self-referencing.

Suppose we have a service class that performs some business logic and needs to call a method on itself as part of that logic:

@Service
public class MyService {
    public void doSomething() {
        // ...
        doSomethingElse();
    }

    @Transactional
    public void doSomethingElse() {
        // ...
    }
}

However, when we run our application, we might notice that @Transactional isn’t applied. This is because the doSomething() method is calling doSomethingElse() directly, which bypasses the Spring proxy.

To work around this, we can use self-injection to get a reference to the Spring proxy and call the method through that proxy.

3. Self-Injection Using @Autowired

We can perform self-injection in Spring by using the @Autowired annotation on a field, constructor parameter, or setter method of a bean.

Here’s an example of using @Autowired with a field:

And with a constructor parameter:

@Component
public class MyBean {
    private MyBean self;

    @Autowired
    public MyBean(MyBean self) {
        this.self = self;
    }

    // ...
}

4. Self-Injection Using ApplicationContextAware

Another way to perform self-injection is by implementing the ApplicationContextAware interface. This interface allows a bean to be aware of the Spring application context and obtain a reference to itself:

@Component
public class MyBean implements ApplicationContextAware {
    private ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.context = context;
    }

    public void doSomething() {
        MyBean self = context.getBean(MyBean.class);
        // ...
    }
}

5. Disadvantages

When a bean injects itself, it can create confusion about the responsibilities of the bean and make it harder to trace the flow of data through the application.

Self-injection can also create a circular dependency. Starting with version 2.6, Spring Boot will raise an exception if our project has circular dependencies. There are some workarounds, of course.

6. Conclusion

In this quick article, we’ve learned several ways we can use self-injection in Spring and when to use it. We’ve also learned some of the disadvantages of self-injection in Spring.