使用@Order注解调整配置类加载顺序

2022年12月2日13:27:54

@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})@Documentedpublic@interfaceOrder{/**
     * 默认是最低优先级
     */intvalue()defaultOrdered.LOWEST_PRECEDENCE;}

常量类:

publicinterfaceOrdered{/**
     * 最高优先级的常量值
     * @see java.lang.Integer#MIN_VALUE
     */int HIGHEST_PRECEDENCE=Integer.MIN_VALUE;/**
     * 最低优先级的常量值
     * @see java.lang.Integer#MAX_VALUE
     */int LOWEST_PRECEDENCE=Integer.MAX_VALUE;intgetOrder();}

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

2.创建三个POJO类Cat、Cat2、Cat3,使用@Component注解将其交给Spring容器自动加载,每个类分别加上@Order(1)、@Order(2)、@Order(3)注解,下面只列出Cat的代码其它的类似

packagecom.eureka.client.co;importorg.springframework.core.annotation.Order;importorg.springframework.stereotype.Component;@Component@Order(1)publicclassCat{privateString catName;privateint age;publicCat(){System.out.println("Order:1");}publicStringgetCatName(){return catName;}publicvoidsetCatName(String catName){this.catName= catName;}publicintgetAge(){return age;}publicvoidsetAge(int age){this.age= age;}}

3.启动应用程序主类

packagecom.eureka.client;importjava.util.Map;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importcom.eureka.client.co.Person;@SpringBootApplicationpublicclassEurekaClientApplication{publicstaticvoidmain(String[] args){SpringApplication.run(EurekaClientApplication.class, args);}}

输出结果是:

Order:1Order:2Order:3
  • 作者:Archie_java
  • 原文链接:https://lebron.blog.csdn.net/article/details/121645670
    更新时间:2022年12月2日13:27:54 ,共 1514 字。