- order的值越小,优先级越高
- order如果不标注数字,默认最低优先级,因为其默认值是int最大值
- 该注解等同于实现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.