Reputation: 265
I have a Spring Boot application which has a bean that needs to send a message (using Spring Cloud Stream) once on startup.
Sending direct from a @PostConstruct
bean method does not work because by that stage it appears that the messaging system is not fully initialised, and an exception results.
I can overcome this using a scheduled task launched from a @PostConstruct
method with a sufficiently long delay, but the key is what constitutes "sufficiently long"; is there an initialisation event published by Spring Cloud Stream that I can listen for which effectively tells me "it's now safe to send a message"?
Failing that, is there a more robust way to handle this than guessing how long the delay should be?
Upvotes: 0
Views: 140
Reputation: 174719
You should never perform "active" operations from a @PostConstruct
method; it's too early in the application context's lifecycle.
Implement SmartLifecycle
, put your bean in a high Phase
(e.g. Integer.MAX_VALUE
) and it will be start()
ed last.
Put your code in the start()
method.
Upvotes: 2