Search code examples
javaspringspring-bootspring-annotations

CommandLineRunner in springboot is not executed


My CommandLineRunner class

package course;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class CourseCommandLineRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("======started ============");
        System.out.println("======doneeee ============");
    }
}

My Main class

package com.jpa.tutorialjpa;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class TutorialJpaApplication{

    public static void main(String[] args) {
        SpringApplication.run(TutorialJpaApplication.class, args);
        System.out.println("======LOADED=");
    }

}

package structure package1 ---Main Class package2 --package2.1 ----CommandLineRunner class

I was expecting my loggers in commandlinerunner will get printed.


Solution

  • Try to put your Runner into same package or a subpackage as the place where your Main class is.

    The primary requirement is that the CommandLineRunner bean is picked up by Spring's Component-Scan. As long as the CommandLineRunner is in a package recognized by Spring Boots Component-Scanning mechanism, it will be executed properly.

    So you have two options.

    1. Move your CommandLineRunner to the package (sub package) of the Main class.

    2. Define the location of the CommandLineRunner via annotation.

        @ComponentScan({"com.example.mypackage","com.jpa.tutorialjpa"})
        @SpringBootApplication
        public class MyMainClass