J.J. Beam
J.J. Beam

Reputation: 3059

What is the best place in SpringBoot application to initialize business logic?

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:

  1. Implement ApplicationListener + listen for ContextStartedEvent
  2. ApplicationRunner's OR CommandLineRunner's run() method
  3. @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

Answers (1)

ozkanpakdil
ozkanpakdil

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

  1. ApplicationListener called 3 times. No need to listen this one. This maybe usefull if you are doing something close to tomcat.
  2. ApplicationRunner,CommandLineRunner is called after all bean initialization. This can be useful.
  3. @PostConstruct you can get null beans if you are working with other components.

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

Related Questions