@Order注解

该博客介绍了如何使用`@Order`注解来控制Spring配置类的加载顺序。通过示例展示了配置类`AConfig`和`BConfig`,其中`BConfig`的加载顺序优先于`AConfig`,因此在程序运行时`BService`先被加载并打印输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@Order注解,用来控制配置类的加载顺序
实例

package com.user.service;

public class AService {

}
package com.user.service;

public class BService {

}
package com.user.config;

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.uer.config;

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.user.test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class OrderMain {
  public static void main(String[] args) {
    AnnotationConfigApplicationContext context =
        new AnnotationConfigApplicationContext("com.uer.config");
  }
}

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值