CommandLineRunner接口具有什么功能呢?
下文笔者讲述commandlinerunner接口的功能简介说明,如下所示
CommandLineRunner接口的功能
CommandLineRunner接口为Spring Boot应用程序启动时运行一些代码
使用CommandLineRunner,可在应用程序启动时执行某些操作
如初始化数据、加载配置或运行其他任务。
通过实现CommandLineRunner接口
您可以轻松地将需要在应用程序启动时提前处理的代码、任务或操作集成到Spring Boot应用程序中
如:
可使用CommandLineRunner接口来加载应用程序的配置文件、初始化数据源、创建Spring ApplicationContext等操作
CommandLineRunner的使用方式
方式1: @Component 方式2: @SpringBootApplication 方式3: 声明一个实现了CommandLineRunner接口Bean
@Component实现CommandLineRunner接口的功能
@SpringBootApplication
public class Demo03Application {
public static void main(String[] args) {
System.out.println("step 1: The Service will start");
SpringApplication.run(Demo03Application.class, args);
System.out.println("step 5: The Service has started");
}
}
@Component
@Order(1)
class Runner1 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("step 3: The Runner1 run...");
}
}
@Component
@Order(2)
class Runner2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("step 4: The Runner1 run...");
}
}
2. @SpringBootApplication实现CommandLineRunner接口的功能
@SpringBootApplication
public class Demo03Application implements CommandLineRunner{
public static void main(String[] args) {
System.out.println("step 1: The Service will start");
SpringApplication.run(Demo03Application.class, args);
System.out.println("step 5: The Service has started");
}
@Override
public void run(String... args) throws Exception {
System.out.println("app start");
}
}
3.@Bean实现CommandLineRunner接口的功能
@SpringBootApplication
public class SpringBootWebApplication extends SpringBootServletInitializer {
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootWebApplication.class, args);
}
@Bean
public ApplicationStartupRunner schedulerRunner() {
return new ApplicationStartupRunner();
}
}
public class ApplicationStartupRunner implements CommandLineRunner {
protected final Log logger = LogFactory.getLog(getClass());
@Override
public void run(String... args) throws Exception {
logger.info("Application Started !!");
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


