Software Development

How does the Spring Framework handle a self-invocation on a creation of beans?

April 10, 2018
by
FINGO

A few weeks ago my workmate asked me a question: “How does the Spring Framework handle a self-invocation on a creation of beans?” He was thinking about a situation like this one:

@Configuration
class MyConfig {

    @Bean
    ABean aBean() {
        return new ABean(this.bBean())
    }
    
    @Bean
    BBean bBean() {
        return new BBean()
    }
}

In this case we see that during the creation of the aBean we invoke a method, which creates the bBean.

From my past experience I know that an invocation of methods on the same bean (self-invocation) will bypass the AOP mechanism. I know that with the AspectJ configured in the Spring framework, self-invocations will work. However, they have implemented it only with the CGLib for @Configuration annotation. How did they achieve this? I had always thought that the Spring Framework uses “normal” aspect-based implementation of the annotations @Bean and @Configuration.

When I realized this situation was true, I thought that I needed to immediately start a mission to research what the magic forces are making the @Configuration work with self-invocations.

I discovered that there is a wizard named the ConfigurationClassEnhancer. This class is responsible for the whole magic. It adds the BeanMethodInterceptor, which makes self-invocation possible. In this case they have chosen to invoke the invokeSuper method in interceptor rather than delegating logic to a aggregated proxy object. This is the reason why the self-invocation on creation of beans work.

During the investigation of the @Configuration incident I have found out that the CGLIB tutorial is very interesting reading.

Do you need regulatory compliance software solutions?

Accelerate your digital evolution in compliance with financial market regulations. Minimize risk, increase security, and meet supervisory requirements.

Do you need bespoke software development?

Create innovative software in accordance with the highest security standards and financial market regulations.

Do you need cloud-powered innovations?

Harness the full potential of the cloud, from migration and optimization to scaling and the development of native applications and SaaS platforms.

Do you need data-driven solutions?

Make smarter decisions based on data, solve key challenges, and increase the competitiveness of your business.

Do you need to create high-performance web app?

Accelerate development, reduce costs and reach your goals faster.