@Order
1、Spring 4.2 利用@Order控制配置类的加载顺序,
2、Spring在加载Bean的时候,有用到order注解。
3、通过@Order指定执行顺序,值越小,越先执行
4、@Order注解常用于定义的AOP先于事物执行
1.@Order的注解源码解读
注解类:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {/*** 默认是最低优先级*/int value() default Ordered.LOWEST_PRECEDENCE;}
常量类:
public interface Ordered {/*** 最高优先级的常量值* @see java.lang.Integer#MIN_VALUE*/int HIGHEST_PRECEDENCE = Integer.MIN_VALUE;/*** 最低优先级的常量值* @see java.lang.Integer#MAX_VALUE*/int LOWEST_PRECEDENCE = Integer.MAX_VALUE;int getOrder();}
注解可以作用在类、方法、字段声明(包括枚举常量);
注解有一个int类型的参数,可以不传,默认是最低优先级;
通过常量类的值我们可以推测参数值越小优先级越高;
2.创建三个POJO类Cat、Cat2、Cat3,使用@Component注解将其交给Spring容器自动加载,每个类分别加上@Order(1)、@Order(2)、@Order(3)注解,下面只列出Cat的代码其它的类似
package com.eureka.client.co;import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;@Component
@Order(1)
public class Cat {private String catName;private int age;public Cat() {System.out.println("Order:1");}public String getCatName() {return catName;}public void setCatName(String catName) {this.catName = catName;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}
3.启动应用程序主类
package com.eureka.client;import java.util.Map;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;import com.eureka.client.co.Person;@SpringBootApplication
public class EurekaClientApplication {public static void main(String[] args) {SpringApplication.run(EurekaClientApplication.class, args);}
}
输出结果是:
Order:1
Order:2
Order:3