Stephen Lin
Stephen Lin

Reputation: 4912

Spring boot use bean inside configuration

@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!

Upvotes: 1

Views: 774

Answers (2)

Bernd Böllert
Bernd Böllert

Reputation: 106

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");
}

Upvotes: 1

Ori Marko
Ori Marko

Reputation: 58772

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

public Binding getMarketingDataSource() {
    return getFactory().getInstance("bindingName");

Upvotes: 1

Related Questions