Reputation: 3059
I want to initialize some business logic (e.g. send some messages to a message broker) in a Spring Boot application after context is created and beans (singletons) are initialized - what is the "most correct" place for it?
From my perspective the candidates are:
ApplicationListener
+ listen for ContextStartedEvent
ApplicationRunner
's OR CommandLineRunner
's run()
method@PostConstruct
of a particular bean (I don't this method, but have seen sometimes in colleagues' code - because I need to be sure all beans are created, initialized, customized, set up, etc. and I don't wanna play with beans load order)I understand that in general, in MVC web application the place for business logic is @Service
, but I need to call it immediately after the start of my application, so what's the best way to do that?
Upvotes: 1
Views: 850
Reputation: 4612
I would go with @EventListener. Like you said there are different ways to achieve this. I will give my opinion on your numbers
I prepared a small example to use all these in one application and print some logs but I could not put them here. spring log looks ugly here. anyway my suggestion is here if you dont have any dependency to other beans this looks nicest. if there are dependencies then you can use ApplicationListener which was the last logged in my example.
Upvotes: 1