Runner启动器

 

Runner启动器的两种创建方式:

  • 实现ApplicationRunner接口,复写run()方法
  • 实现CommandLineRunner接口,复写run()方法

 

Runner启动器的执行顺序

  如果一个项目中包含多个启动器,可以让启动器类实现 org.springframework.core.Ordered接口或者使用 org.springframework.core.annotation.Order注解类来注解启动器类。项目启动时会按照指定的order升序执行。

 

Runner启动器的创建示例

示例一:实现ApplicationRunner接口

package com.huang.pims.demo.runners;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(value = 1)
public class ApplicationRunnerDemo implements ApplicationRunner, Ordered {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationRunnerDemo.class);

    @Override
    public void run(ApplicationArguments args) throws Exception {
        LOGGER.info("order:{} ApplicationRunnerDemo.run()...", getOrder());
    }

    @Override
    public int getOrder() {
        return 1;
    }
}

 

示例二:实现CommandLineRunner接口

package com.huang.pims.demo.runners;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

@Component
public class CommandLineRunnerDemo implements CommandLineRunner, Ordered {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommandLineRunnerDemo.class);


    @Override
    public void run(String... args) throws Exception {
        LOGGER.info("order:{} CommandLineRunner.run()...", getOrder());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

 

  以上两种创建方式,都需要使用@Component注解将之添加到Spring IOC容器中,这样,项目在启动时就会自动执行Runner启动器中的run()方法。

启动项目后的效果如下:

 

posted @ 2019-05-29 14:35  狱婪  阅读(251)  评论(0编辑  收藏  举报