简体   繁体   中英

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!

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM