码迷,mamicode.com
首页 > 其他好文 > 详细

@Order

时间:2020-05-02 20:42:57      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:toc   efault   shu   ted   测试   获得   str   etc   接下来   

注解@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

作者:氨基钠
链接:https://www.jianshu.com/p/37edf9389814
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

@Order

标签:toc   efault   shu   ted   测试   获得   str   etc   接下来   

原文地址:https://www.cnblogs.com/kikochz/p/12819300.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!