0

I have the following java config class:

@Configuration
public class MyConfig {

    @Autowired
    private List<MyInterface> myInterfaces;

    @Bean
    public A a() {
        return new A();
    }

    @PostConstruct
    public void postConstruct() {
        a().setProperty(myInterfaces);
    }
}

Each MyInterface implementation will have a dependency on bean A, which I assume is where this circular dependency is coming from; my expectation, however, was as follows:

  1. This configuration class instantiates A and adds it to the application context
  2. The implementations of MyInterface are successfully injected with bean A
  3. The list of MyInterface implementations are injected into MyConfig
  4. The @PostConstruct executes, setting myInterfaces on bean A

Can anyone shed some light on which of my assumptions is incorrect?

1 Answer 1

1

You have a circular dependency in your code: remember that MyConfig is a bean as well so it needs to be instantiated and autowired. In order for it to be created, it needs to be injected with all available MyInterface instances, one of which requires bean A, which is created by an instance method of MyConfig and so on.

If you were to run in Spring Boot 1.4+, you would get this output:

***************************
APPLICATION FAILED TO START
***************************

Description:

    The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  interfaceImpl defined in file [/.../InterfaceImpl.class] 
↑     ↓
|  myConfig (field private java.util.List demo.MyConfig.myInterfaces)
└─────┘

You have two options :

  • make public A a() { -> public static A a() { (thus not requiring bean A to be created by an instance method of MyConfig);
  • make myInterfaces a @Lazy dependency (so that is actually populated only when accessed): e.g.

    @Autowired @Lazy
    private List<MyInterface> myInterfaces;
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.