简体   繁体   中英

How to run CommandLineRunner in spring boot

I'm working on an application using spring. I expect its run to be called when the app starts. But it doesn't seem work even if the code and the setting is both ok. Here's the code.

package mrs;

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

@SpringBootApplication
public class SpringJpa2Application {

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

}
package config;

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

import mrs.model.Comment;
import mrs.repository.CommentRepository;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@Component
public class DataLoader implements CommandLineRunner{
    private final CommentRepository repository;
    
    @Override
    public void run(String... args) throws Exception{
        System.out.println("start");

        //doSomething

        System.out.println("done");
    }
}

Is Spring scanning your config package? Try adding:

@SpringBootApplication(scanBasePackages = { "config" })

to your SpringBootApplication annotation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM