淺談Spring @Order註解的使用

註解@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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章