常用注解使用总结系列: @Order 注解

时间:2022-07-24
本文章向大家介绍常用注解使用总结系列: @Order 注解,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

@Order 注解

@Order注解主要用来控制配置类的加载顺序 示例代码:

package com.runlion.tms.admin.constant;

public class AService {

}
package com.runlion.tms.admin.constant;

public class BService {

}
package com.runlion.tms.admin.constant;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Configuration
@Order(2)
public class AConfig {
  @Bean
  public AService AService() {
    System.out.println("AService 加载了");
    return new AService();
  }

}
package com.runlion.tms.admin.constant;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

@Configuration
@Order(1)
public class BConfig {
  @Bean
  public BService bService() {
    System.out.println("BService 加载了");
    return new BService();
  }
}

测试类:

package com.runlion.tms.admin.constant;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class OrderMain {
  public static void main(String[] args) {
    AnnotationConfigApplicationContext context =
        new AnnotationConfigApplicationContext("com.runlion.tms.admin.constant");
  }
}

输出结果: BService 加载了 AService 加载了

因为BService 的@Order(1),所以先打印出来