0%

spring | @Order

@Order 通常和 spring boot | 接口 CommandLineRunner 还有 spring | 注解 @component @Repository @Service @Controller 一起使用。

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

@Order源码

1
2
3
4
5
6
7
8
9
10
11
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {

/**
* 默认是最低优先级,值越小优先级越高
*/
int value() default Ordered.LOWEST_PRECEDENCE;

}
  • 注解可以作用在类(接口、枚举)、方法、字段声明(包括枚举常量);
  • 注解有一个int类型的参数,可以不传,默认是最低优先级;
  • 通过常量类的值我们可以推测参数值越小优先级越高;

Order 接口类

1
2
3
4
5
6
7
8
package org.springframework.core;

public interface Ordered {
int HIGHEST_PRECEDENCE = -2147483648;
int LOWEST_PRECEDENCE = 2147483647;

int getOrder();
}

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Component
@Order(1)
public class BlackPersion implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("----BlackPersion----");
}
}

@Component
@Order(0)
public class YellowPersion implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("----YellowPersion----");
}
}

输出

1
2
----YellowPersion----
----BlackPersion----

我们可以通过调整@Order的值来调整类执行顺序的优先级,即执行的先后;当然也可以将@Order注解更换为Ordered接口,效果是一样的

注入顺序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.lou.springboot;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


interface ComponentConsumer<T> {
boolean deal(T t);
}

@Component
@Order(2)
class EatComponent implements ComponentConsumer<Message> {

private static final Logger logger = LoggerFactory.getLogger(Component.class);

@Override
public boolean deal(Message message) {
return message.getEat();
}
}

@Component
@Order(3)
class SleepComponent implements ComponentConsumer<Message> {

private static final Logger logger = LoggerFactory.getLogger(Component.class);

@Override
public boolean deal(Message message) {
return message.getSleep();
}
}

@Component
@Order(1)
class PlayComponent implements ComponentConsumer<Message> {

private static final Logger logger = LoggerFactory.getLogger(Component.class);

@Override
public boolean deal(Message message) {
return message.getPlay();
}
}

@Service
public class ServiceImpl {

@Resource
List<ComponentConsumer> componentConsumerList;
}

componentConsumerList 的注入顺序是

  • play
  • eat
  • sleep
请我喝杯咖啡吧~