1
@Configuration
@AutoConfigureOrder()
@ComponentScan("scanPath")
public class AutoConfiguration {    

    @Autowired
    private Factory   factory;

    @Bean("factory")
    @ConditionalOnProperty(prefix = "application.middleware", name = "enabled", havingValue = "true")
    public Factory getFactory() {
        return new Factory();
    }

    @Bean("binding")
    @DependsOn("factory")
    public Binding getMarketingDataSource() {
        return factory.getInstance("bindingName");
    }
}    

I'd like to: 1. init bean factory (could be null if no value found) 2. autowired and used by bean binding

But right now I get exception

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

So what I want is using factory in binding, how to make it? Thanks!

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
Stephen Lin
  • 4,852
  • 1
  • 13
  • 26
  • 1
    circular dependencies are the fruit of faulty designs. https://stackoverflow.com/questions/10008714/requested-bean-is-currently-in-creation-is-there-an-unresolvable-circular-refer – Vishwa Ratna Sep 02 '19 at 13:24
  • 1
    You can just use `getFactory` or use `Factory` as a method argument. You don't need to autowire it. Autowiring fails because you are injecting it into the configuration that creates it as well. To inject the bean needs to be there and to create a valid `@Configuration` the bean is needed, hence the circulair dependency. – M. Deinum Sep 02 '19 at 13:29

2 Answers2

1

Use getFactory() to get the Bean (and remove @Autowired):

public Binding getMarketingDataSource() {
    return getFactory().getInstance("bindingName");
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
1

Wire the factory in the signature, now Spring sees that binding needs factory and sets it for you:

@Bean("binding")
public Binding getMarketingDataSource(Factory factory) {
  return factory.getInstance("bindingName");
}