Java – BeanCurrentlyInCreationException when @Autowired and @Bean are present in same class

autowiredcircular-dependencyjavajavabeansspring

@Configuration
public class Test1 {

    @Autowired
    private Test3 test3;

}

@Configuration
public class Test2 {

    @Autowired
    private Test3 test3;

    @Bean(name = "test3 ")
    Test3 test3 () {
        return new Test3(); 
    }
}

The above code gives the following error.

Caused by:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'test1': Injection of autowired dependencies failed;
nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private Test3 com.package.name.Test1.test3;

nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'test2': Injection of autowired dependencies failed;
nested exception is
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private Test3 com.package.name.Test2.test3;

nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'test3': Requested bean is currently in creation: Is there an unresolvable circular reference?

How is this an example of circular dependency? If it is, any ideas on resolving this.

Best Answer

You don't need to autowire a bean defined in the same class since you can just reference that bean directly by calling the initialising method test3().

@Configuration
public class Test2{

    @Bean(name = "test3 ")
    Test3 test3 () {
        return new Test3(); 
    }

    public void exampleOfUsingTest3Bean() {
        System.out.println("My test3 bean is" + test3().toString());
    }
}

And, indeed, you should not do what you were trying to do since @Autowired fields are injected into a class on construction of the class and at this point no bean called Test3 exists because it is defined by a method of the class being constructed. Theoretically you could define this @Bean method to be static and it should be available to autowire but you shouldn't do this.

@Bean(name = "test3 ")
public static Test3 test3 () {
    return new Test3(); 
}
Related Topic