详谈SpringBoot启动项目后执行自定义方法的方式

在 main 启动函数中调用

这个是在所有启动后执行,也是常用之一。

@SpringBootApplication
public class ListenerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ListenerApplication.class, args);
        System.out.println("启动成功");
    }
}

实现 CommandLineRunner 接口

项目初始化完毕后才会调用方法,提供服务。好处是方法执行时,项目已经初始化完毕,是可以正常提供服务的。

@Component
public class CommandLineRunnerImpl implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(Arrays.toString(args));
    }
}

实现 ApplicationRunner 接口

实现 ApplicationRunner 接口和实现 CommandLineRunner 接口基本是一样的。不同的是启动时传参的格式,CommandLineRunner 对于参数格式没有任何限制。

ApplicationRunner 接口参数格式必须是:key=value

@Component
public class ApplicationRunnerImpl implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Set optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            List values = args.getOptionValues(optionName);
            System.out.println(values.toString());
        }
    }
}

注意

CommandLineRunner 和 ApplicationRunner 默认是 ApplicationRunner 先执行,如果双方指定了@Order 则按照 @Order 的大小顺序执行,大的先执行。

实现 ApplicationListener 接口

实现 ApplicationListener 接口和实现 ApplicationRunner、CommandLineRunner 接口基本差不多,项目初始化完毕后才会调用方法,提供服务。

@Component
public class ApplicationListenerImpl implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        System.out.println("ApplicationStartedEvent");
    }

}

当以 @Component 方式配置时,事件触发顺序如下:

ApplicationListener
ApplicationListener
ApplicationListener
ApplicationListener
ApplicationListener

当通过 /META-INF/spring.factories 配置时,事件触发顺序如下:

org.springframework.context.ApplicationListener=com.xh.event.ApplicationListenerImpl

ApplicationListener
ApplicationListener
ApplicationListener
ApplicationListener
ApplicationListener
ApplicationListener
ApplicationListener
ApplicationListener
ApplicationListener

注意 

  • 如果监听的是 ServletWebServerInitializedEvent、ContextRefreshedEvent、ApplicationStartedEvent 事件,则 ApplicationListener 会在 CommandLineRunner 和 ApplicationRunner 之前执行
  • 如果监听的是 ApplicationReadyEvent 事件,则 ApplicationListener 会在 CommandLineRunner 和 ApplicationRunner 之后执行
  • ContextClosedEvent 当调用关闭方法的时候,才会触发了 ContextClosedEvent 事件

实现 InitializingBean 接口

项目启动时,调用此方法,在 ServletWebServerInitializedEvent 事件前触发。

@Component
public class InitializingExample implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingExample");
    }
}

@PostConstruct 注解

使用注解 @PostConstruct 实现,不推荐使用。如果执行的方法耗时过长,会导致服务无法提供服务。

@Component
public class StartBoot {

    @PostConstruct
    public void init() throws InterruptedException {
        System.out.println("@PostConstruct");
    }
}

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