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

2022年11月23日10:59:59

@Order 注解

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

package com.runlion.tms.admin.constant;publicclass AService {

}
package com.runlion.tms.admin.constant;publicclass BService {

}
packagecom.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();
  }

}
packagecom.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;publicclassOrderMain {publicstaticvoidmain(String[] args) {
    AnnotationConfigApplicationContext context =new AnnotationConfigApplicationContext("com.runlion.tms.admin.constant");
  }
}

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

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

  • 作者:程序员陆通
  • 原文链接:https://lulutongtong.blog.csdn.net/article/details/80375786
    更新时间:2022年11月23日10:59:59 ,共 1148 字。