Persimmonium
Persimmonium

Reputation: 15771

how to add a dynamically created bean in a @PostConstruct in Spring Boot

I need to add a dynamically created bean when my 'normal' bean gets created. I tried this so far:

//generate a health bean dynamically, and register it
@PostConstruct
public void init(){
    solrhealth = new SolrHealthIndicator(solr);
    //context.??
}

I build a SolrHealthIndicatior bean programatically, as I am not using Spring Solr Data. Now I want it registered so it shows up in /health.

I have my context wired, but cannot find how to register the newly created bean in there...

Upvotes: 2

Views: 6278

Answers (3)

Magnus
Magnus

Reputation: 8300

You should be able to programatically define your bean by using the @Bean annotation within a @Configuration class.

@Bean
public SolrHealthIndicator solrHealthIndicatior() {
    //you can construct the object however you want
    return new SolrHealthIndicator();
}

Then you can just inject it like any other bean(@Autowired constructor, field, setter injection, etc.), if there are multiple beans with the same type you can use @Qualifier to distinguish between them.

Upvotes: 2

Ben M
Ben M

Reputation: 1892

You could make the class containing your @PostConstruct implement BeanDefinitionRegistryPostProcessor. Then you'd then be able to register your beans programmatically:

@Bean
public class MyBean implements BeanDefinitionRegistryPostProcessor {

    private BeanDefinitionRegistry registry;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        this.registry = registry;
    }

    @PostConstruct
    public void init(){
        registry.registerBeanDefinition("solrHealthIndicator", new SolrHealthIndicator(solr));
    }
}

Upvotes: 1

yaswanth
yaswanth

Reputation: 2477

You need to use @Lookup annotation.

@Component
public class SolrHealthIndicator {

    public SolrHealthIndicator(Solr solr) {

    }
}


public class BeanInQuestion {

    @PostConstruct
    public void init() {
        solrHealthIndicator = getHealthIndicatorBean();
    }

    @Lookup
    public SolrHealthIndicator getHealthIndicatorBean() {
        //Spring creates a runtime implementation for this method
        return null;
    }

}

Upvotes: 2

Related Questions