Run code on Spring Boot App Startup

Munish Chandel | July 27, 2018 at 05:41 PM | 269 views | spring-boot


Running code on app startup is a typical requirement in many scenarios like initializing some DB related stuff, triggering notification about container startup etc.

There are multiple ways to achieve this in Spring Boot -

  1. Using @Postconstruct method in singleton bean.

  2. Using ApplicationEvent - ApplicationReadyEvent or ContextRefreshEvent.

  3. Using CommandLineRunner

  4. Using ApplicationRunner

Using @PostConstruct

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. The init() method will not be called until any autowiring is done for the bean service.

@Component
public class Monitor {
    @Autowired
    private SomeService service

    @PostConstruct
    public void init(){
        // start your monitoring in here
    }
}

Be noted that this method must not have any parameters.

Using CommandLineRunner

CommandLineRunner can be used to run code at application startup, provided it should be contained within SpringApplication. So if you are running program from a war file hosted inside a servlet container (instead of spring boot embedded containers), there may be problems.

Using Bean style approach:

@SpringBootApplication
public class Application {
	private static final Logger log = LoggerFactory.getLogger(Application.class);

	public static void main(String[] args) {
		SpringApplication.run(Application.class);
	}

	@Bean
	public CommandLineRunner demo(CustomerRepository repository) {
		return (args) -> {
			// save a couple of customers
		};
	}
}

Using a component approach, code might look different:

Using CommandLineRunner
@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(CommandLineAppStartupRunner.class);

    @Override
    public void run(String...args) throws Exception {
        logger.info("Application started with command-line arguments: {} . \n To kill this application, press Ctrl + C.", Arrays.toString(args));
    }
}

Using ApplicationRunner

CommandLineRunner does not provide access to ApplicationArguments, if we need access to access to ApplicationArguments instead of raw string array, then we can use ApplicationRunner.

@Component
public class ApplicationRunnerBean implements ApplicationRunner {
	@Override
	public void run(ApplicationArguments arg0) throws Exception {
		System.out.println("ApplicationRunnerBean");
	}
}

Using ApplicationEvent in Spring Boot

Spring framework publishes event for ApplicationReadyEvent, which gets fired when the application is ready to service requests.

@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
    System.out.println("hello world, I have just started up");
}
Use a SmartInitializingSingleton bean in spring > 4.1

SmartInitializingSingleton Callback interface triggered at the end of the singleton pre-instantiation phase during BeanFactory bootstrap.

@Bean
public SmartInitializingSingleton importProcessor() {
    return () -> {
        doStuff();
    };

}

Order of execution for multiple startup beans

Multiple CommandLineRunner/ApplicationRunner beans can be made to execute in a certain order at app startup using @Order annotation.

The bean with lowest order value will have the highest priority and hence will run before beans with higher order value. Default order value is Integer.MAX_VALUE which has lowest PRECEDENCE, hence will run in the last.

In the below code, CmdAppStartupRunner1 will run first and then CmdAppStartupRunner2

Multiple Beans execution in a pre-defined order
@Order(1)
@Component
public class CmdAppStartupRunner1 implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(CmdAppStartupRunner1.class);

    @Override
    public void run(String... args) {
        logger.info("Application started with command-line arguments: {} . " +
                "\n To kill this application, press Ctrl + C.", Arrays.toString(args));
    }
}

@Order(2)
@Component
public class CmdAppStartupRunner2 implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(CmdAppStartupRunner2.class);

    @Override
    public void run(String... args) {
        logger.info("Application started with command-line arguments: {} . " +
                "\n To kill this application, press Ctrl + C.", Arrays.toString(args));
    }
}

Buy DRM Free PDF for Complete Collection of Interview Questions
Generic placeholder image
ebook PDF - Cracking Java Interviews v3.4 by Munish Chandel

240 real Java interview questions on core Java, concurrency, algorithms, design & data structures, spring, hibernate for Investment Bank, Healthcare IT, product and service based companies, Author : Munish Chandel, Price: 250, Type: PDF

Free Email Updates
Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.


Similar Articles:
  1. How to create a custom banner for your spring boot application
  2. Run code on Spring Boot App Startup
  3. Spring Boot 2.0 Reactive Web Performance Metrics
Facebook Page
Free Email Updates (100+ Subscribers)

Enter your email address to subscribe to this blog and receive notifications of new posts by email.


This website uses cookies to ensure you get the best experience on our website. more info