Search code examples
javaspringspring-mvc

How to write startup logic which does not create a bean to run during spring configuration lifecycle?


In addition to traditional beans that were configuring with @configuration and @bean we have some startup logic in our code which must be done at bootup, things like running liquibase on the database, loading configuration data from files into database, and performing some sanity tests. None of this is really associated with a Bean that will autowired afterwards, the changes are being persisted via the database not spring. However, there is a good amount of it to be done. Much of it is also dependent on earlier steps having completed and/or services being autowired.

What is the best way to do this within a spring context? I know that there is an ApplicationContextAware we could use to start this logic, but it doesn't seem appropriate because of a few reasons

  1. it would run an applicationcontext refresh, not just at bootup
  2. This would allow running just one class, I'd prefer to be able to write logic the way we do @configuration where I can toss in a new component and have it run where appropriate
  3. In at least one case we have a bean that we can't properly configure until some of the database configuration is done, meaning we want this configuration logic to run in the middle of the spring bootup, not at the end.

Currently the approach we have is a @Configuration class that has no @bean method, instead using afterPropertiesSet() to run a database configuration file that sequentially goes through each database configuration phase in a large configure method. This does work pretty well, but it feels like it's breaking the intended use of @configuration to be used explicitly for creating @bean definitions for later autowiring.

Does spring provide a better approach for being able to plus non-bean configuration into the middle of it's configuration/autowire phase, or is this the best approach available?

To answer the question in the comment this is a restful web application using spring-mvc. It's a war started when the web server is started.


Solution

  • I was having similar requirements where I wanted to fetch the Records from DB and put it into my Cache whenever my Server starts and I achieved it by writing a method in my Service Class and annotating it as @PostConstruct. What will happen is that once the Bean Creation is done then this method will execute and it will execute only once after the bean creation or during the Server Startup.

    It is very simple as you need not to write a separate class and you can do it simply by creating an additional method in your Controller/Service Class.