Home » Java » java – CommandLineRunner functionality in Spring MVC application-Exceptionshub

java – CommandLineRunner functionality in Spring MVC application-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

We have a Spring MVC project with multiple Maven modules. We package it into an EAR and deploy it to a WildFly server.

I am trying to do a single time job on project start up. Thus, I thought about the CommandLineRunner interface, the project would compile and run but the commandLineRunner run method wouldn’t run.

I guess it’s because we are using an MVC Spring project and not a SpringBoot one with its own embedded server.
Can you suggest any ways to implement such a concept in Spring MVC ?

Thanks.

How to&Answers:

You can do something like that:

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class StartupExec implements {

  @EventListener(ContextRefreshedEvent.class)
  public void contextRefreshedEvent() {
    // do whatever you need here 
  }
}

This is from this answer.