SpringBoot之Order注解启动顺序说明

order的规则:

  1. order的值越小,优先级越高
  2. order如果不标注数字,默认最低优先级,因为其默认值是int最大值
  3. 该注解等同于实现Ordered接口getOrder方法,并返回数字。
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {

	/**
	 * The order value.
	 * <p>Default is {@link Ordered#LOWEST_PRECEDENCE}.
	 * @see Ordered#getOrder()
	 */
	int value() default Ordered.LOWEST_PRECEDENCE;

}
int LOWEST_PRECEDENCE = Integer.MAX_VALUE;
@Aspect
@Component
public class DataSourceAspect implements Ordered {
   
    @Override
    public int getOrder() {
        return 1;
    }

}

见下:

OrderRunner1.java

@Component
@Order(1)
public class OrderRunner1 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("The OrderRunner1 start to initialize ...");
    }
}

OrderRunner2.java

@Component
@Order(2)
public class OrderRunner2 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("The OrderRunner2 start to initialize ...");
    }
}

Runner.java

@Component
public class Runner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("The Runner start to initialize ...");
    }
}
@SpringBootApplication
public class CommandLineRunnerApplication {

	public static void main(String[] args) {
		System.out.println("The service to start.");
		SpringApplication.run(CommandLineRunnerApplication.class, args);
		System.out.println("The service has started.");
	}
}

它们的启动日志:

The service to start.
...
...
The OrderRunner1 start to initialize ...
The OrderRunner2 start to initialize ...
The Runner start to initialize ...
The service has started.
收藏 (0)
评论列表
正在载入评论列表...
我是有底线的
为您推荐
    暂时没有数据