springboot-springboot interview questions and answers series 3

1. The purpose of this post

I would show some questions and answers of springboot interviews.

2. Environments

  • springboot 1.x and 2.x

3. Springboot Interview Questions and Answers Series 3

3.1 How do I run some specific code when Spring Boot starts??

Sometimes, we want to run some specific code when springboot app starts,there are two ways to do this job:

3.1.1 Implements the CommandLineRunner

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;

public class MyCommand implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(MyCommand.class);

    public void run(String... strings) throws Exception {
        logger.info("MyCommand run");

3.1.2 Implements the ApplicationRunner

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

 * Created on 2019/5/22.
public class MyAppRunner implements ApplicationRunner {
    private static Logger logger = LoggerFactory.getLogger(MyAppRunner.class);

    public void run(ApplicationArguments args) throws Exception {
        logger.info("MyAppRunner run with {} ",
        logger.info("# NonOptionArgs: " + args.getNonOptionArgs().size());


        logger.info("# OptionArgs: " + args.getOptionNames().size());

        args.getOptionNames().forEach(optionName -> {
            logger.info(optionName + "=" + args.getOptionValues(optionName));