浅谈Spring @Order注解的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yaomingyang/article/details/86649072

注解@Order的作用是定义Spring容器加载Bean的顺序,接下来我们通过分析源码和示例测试详细的学习。

1.@Order的注解源码解读

注解类:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Documented
public @interface Order {

	/**
	 * 默认是最低优先级
	 */
	int value() default Ordered.LOWEST_PRECEDENCE;

}

常量类:

public interface Ordered {

	/**
	 * 最高优先级的常量值
	 * @see java.lang.Integer#MIN_VALUE
	 */
	int HIGHEST_PRECEDENCE = Integer.MIN_VALUE;

	/**
	 * 最低优先级的常量值
	 * @see java.lang.Integer#MAX_VALUE
	 */
	int LOWEST_PRECEDENCE = Integer.MAX_VALUE;

	int getOrder();

}
  • 注解可以作用在类、方法、字段声明(包括枚举常量);
  • 注解有一个int类型的参数,可以不传,默认是最低优先级;
  • 通过常量类的值我们可以推测参数值越小优先级越高;
2.创建三个POJO类Cat、Cat2、Cat3,使用@Component注解将其交给Spring容器自动加载,每个类分别加上@Order(1)、@Order(2)、@Order(3)注解,下面只列出Cat的代码其它的类似
package com.eureka.client.co;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class Cat {
	
	private String catName;
	private int age;
	
	public Cat() {
		System.out.println("Order:1");
	}
	public String getCatName() {
		return catName;
	}
	public void setCatName(String catName) {
		this.catName = catName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
3.启动应用程序主类
package com.eureka.client;

import java.util.Map;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.eureka.client.co.Person;

@SpringBootApplication
public class EurekaClientApplication {

	public static void main(String[] args) {
		SpringApplication.run(EurekaClientApplication.class, args);

	}
}

输出结果是:

Order:1
Order:2
Order:3

猜你喜欢

转载自blog.csdn.net/yaomingyang/article/details/86649072