Spring Boot CommandLineRunner/ApplicationRunner

Spring boot 的最基本的操作就是执行一个进程 也就是 CommandLineRunner。如果要使用spring batch 那么就可以研究下spring boot batch 参考另一篇博文

CommandLineRunner.java

你需要做的就是实现run() 方法,并不是一个线程
你可以使用Order(num)来实现流程的控制。
原型为下:

#CommandLineRunner.java 

public interface CommandLineRunner {
    void run(String... var1) throws Exception;
}

#ApplicationRunner.java
public interface ApplicationRunner {
    void run(ApplicationArguments var1) throws Exception;
}

下面是CommandLineRunner的例子:

  1. SpiderBatchApplication.java

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
    import org.springframework.context.annotation.Bean;
    
    @EnableAutoConfiguration
    @SpringBootApplication
    public class SpiderBatchApplication {
    
        private static final Logger logger = LoggerFactory.getLogger(SpiderBatchApplication.class);
    
        /**
         * 
         * @param args
         * @throws Exception
         */
        public static void main(String[] args) throws Exception {
            // System.exit is common for Batch applications since the exit code can be used to
            // drive a workflow
            logger.info("======================");
            System.exit(SpringApplication
                    .exit(SpringApplication.run(SpiderBatchApplication.class, args)));
        }
    
    }
    
  2. Task1.java

    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    @Component
    @Order(2)
    public class Task1 implements CommandLineRunner {
    
        @Override
        public void run(String... strings) throws Exception {
            System.out.println("task11111111111");
        }
    }
    
    
  3. Task2.java

    
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    
    /**
     * Created with IntelliJ IDEA.
     * User: leo
     * Date: 2017/11/10
     * Time: 10:15
     * To change this template use File | Settings | File Templates.
     */
    @Component
    @Order(1)
    public class Task2 implements CommandLineRunner {
    
        @Override
        public void run(String... strings) throws Exception {
            System.out.println("task2222222222");
        }
    }
    

你可能感兴趣的:(Spring Boot CommandLineRunner/ApplicationRunner)