注解@Order或者接口Ordered的作用是定义Spring IOC容器中Bean的执行顺序的优先级,而不是定义Bean的加载顺序,Bean的加载顺序不受@Order或Ordered接口的影响;
注解源码解读:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {
/**
* 默认是最低优先级,值越小优先级越高
*/
int value() default Ordered.LOWEST_PRECEDENCE;
}
示例代码:
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");
}
}