circular dependency in spring bean

52 Views Asked by At

I created two versions of this code (started learning Java Spring this week):

//version 1 (Complete)
public class Mello {
    public void fun2()
    {
        System.out.println("inside mello");
    }
}
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;


@Configuration
public class Hello
{
    Mello mello;

    @Bean
    public Mello mello()
    {
        return new Mello();
    }

    public Hello(Mello mello)
    {
        this.mello = mello;
    }

    @Bean
    public Hello name()
    {
        return new Hello(mello());
    }

    public void fun()
    {
        this.mello.fun2();
        System.out.println("Hello World!");
    }
}
package org.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main 
{
    public static void main(String[] args) 
    {

        ApplicationContext context = new AnnotationConfigApplicationContext(Hello.class);
        Hello obj = (Hello)context.getBean("name");

        obj.fun();
    }
}

This above code gives an error of "having circular dependency".

//Version 2 (updating "Hello" class & eliminating the use of "mello" class)

package org.example;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

@Configuration
public class Hello
{

    @Bean
    public Hello name()
    {
        return new Hello();
    }
}

Version 2 is totally error free.

Now, for version 1, I can only assess that the error is happening as when "name" bean is identified by spring, it goes on creating the object for "Hello" class inside the method, on finding that a dependency exist ("mello" bean) - it checks the container for a bean of type "mello" - NOW it checks the container registry to know how to create a "Hello" bean? It refers back to its registry and finds that the Hello bean is created using the "name" method.

Re-invocation of name method: Thus, Spring invokes the name method again, which in turn leads back to creating a loop (circular dependency).

Please let me know if I am on the correct/incorrect path. Thanks!

0

There are 0 best solutions below