heuts
heuts

Reputation: 117

Initialize Bean after application start when external dependency is ready

I have a bean that start some amqp consumers.

This bean is registered and initialized in the constructor of a @Configuration class like so:

@Autowired
ApplicationContext applicationContext

...

ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton(consumingIntegrationBeanName, consumingIntegration);
beanFactory.initializeBean(consumingIntegration, consumingIntegrationBeanName);

However the consumer process that is started when doing this, is dependant on an api that is starting simultaniously in a separate process.

I am thinking to do something like this:

while (!isInitialized) {
    Response response = httpClient.isAlive(http://api-in-separate-process/);
    if (response.status == 200) {
        beanFactory.initializeBean(consumingIntegration, consumingIntegrationBeanName);
        isInitialized = true;
    } else {
        wait 10
    }
}

But where would one place something like this? The rest of the application should not be affected by the delayed start of this specific bean.

Upvotes: 0

Views: 365

Answers (1)

Angelo Immediata
Angelo Immediata

Reputation: 6954

What I would do is the following thing: when the "api-in-separate-process" is totally started I generate a kind of message (e.g. JMS message). In the other spring context (where the consumer should be started) I put a listener on the generated message (e.g. the JMS message in previous sentence).

This listener starts consumers when it receives the message (e.g. the JMS message)

Angelo

Upvotes: 1

Related Questions