Spring-Boot ApplicationRunner & CommandLineRunner 接口

有时候需要在Springboot启动后执行某操作,实现ApplicationRunner和CommandLineRunner接口(都有run方法)就可以解决这个问题。

所有实现这两个接口的,如果要执行一系列操作,可以通过实现Ordered接口或用Order注解来指定执行顺序(默认从小到大开始执行)。

Spring-Boot ApplicationRunner & CommandLineRunner 接口_第1张图片

Spring-Boot ApplicationRunner & CommandLineRunner 接口_第2张图片

2. 示例:

主类:

package iot.lcn.com.example;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@Slf4j
@SpringBootApplication
public class ExampleApplication implements CommandLineRunner{
	public static void main(String[] args) {
		SpringApplication.run(ExampleApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		log.error("I'm in main class");
	}
}

另外两个类相似:

package iot.lcn.com.example.abc;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Order(value = 1)
public class CLR1 implements CommandLineRunner{
    @Override
    public void run(String... args) throws Exception {
        log.error("I'm CLR 1");
    }
}

输出结果: 

2019-09-02 16:40:33.744 [main] INFO  o.s.scheduling.concurrent.ThreadPoolTaskExecutor - Initializing ExecutorService 'applicationTaskExecutor'
2019-09-02 16:40:34.168 [main] INFO  org.apache.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8080"]
2019-09-02 16:40:34.246 [main] INFO  o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat started on port(s): 8080 (http) with context path ''
2019-09-02 16:40:34.254 [main] INFO  iot.lcn.com.example.ExampleApplication - Started ExampleApplication in 5.376 seconds (JVM running for 7.846)
2019-09-02 16:40:34.259 [main] ERROR iot.lcn.com.example.abc.CLR1 - I'm CLR 1
2019-09-02 16:40:34.260 [main] ERROR iot.lcn.com.example.abc.CLR2 - I'm CLR 2
2019-09-02 16:40:34.260 [main] ERROR iot.lcn.com.example.ExampleApplication - I'm in main class

 

你可能感兴趣的:(Spring,Java)