两种Spring Boot 项目启动自动执行方法的实现方式

776 阅读1分钟

实际应用场景:springboot项目启动成功后执行一段代码,如系统常量,配置、代码集等等初始化操作;执行多个方法时,执行顺序使用Order注解或Order接口来控制。

Springboot给我们提供了两种方式

第一种实现ApplicationRunner接口

package org.mundo.demo.core;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(2)
public class ApplicationRunnerImpl implements ApplicationRunner {
	@Override
	public void run(ApplicationArguments args) throws Exception {
		System.out.println("通过实现ApplicationRunner接口,在spring boot项目启动后执行代码...");
	}
}

第二种实现CommandLineRunner接口

package org.mundo.demo.core;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class CommandLineRunnerImpl implements CommandLineRunner {
	@Override
	public void run(String... args) throws Exception {
		System.out.println("通过实现CommandLineRunner接口,在spring boot项目启动后执行代码...");
	}
}

对比:

    相同点:这两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方法,都是在SpringApplication 执行之后开始执行的。

    不同点:CommandLineRunner接口可以用来接收字符串数组的命令行参数,ApplicationRunner 是使用ApplicationArguments 用来接收参数的

注意:

1、执行顺序可以使用注解@Order或者Ordered接口,注解@Order或者接口Ordered的作用是定义Spring IOC容器中Bean的执行顺序的优先级,而不是定义Bean的加载顺序,Bean的加载顺序不受@Order或Ordered接口的影响;

2、当项目中同时实现了ApplicationRunner和CommondLineRunner接口时,可使用Order注解或实现Ordered接口来指定执行顺序,值越小,越优先执行

3、注解有一个int类型的参数,可以不传,默认是最低优先级;