浅析java - ordered用法

java核心标题 Ordered

Spring中提供了一个Ordered接口。Ordered接口,顾名思义,就是用来排序的。
Spring是一个大量使用策略设计模式的框架,这意味着有很多相同接口的实现类,那么必定会有优先级的问题。
于是,Spring就提供了Ordered这个接口,来处理相同接口实现类的优先级问题。

代码实现

1.首先创建一个spring boot 项目。
写一个接口,叫Example 吧,继承 Ordered这个类。
在这里插入图片描述
2.创建几个类,实现这个接口。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3,加上一个排序的类,SpringContext。

/**
 * @name : wkk
 * @description:
 * @author: Andy
 * @time: 2020/12/9 18:49
 */
@Component
public class SpringContext implements ApplicationContextAware {
    
    

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    
    
        this.applicationContext = applicationContext;
    }

    public static  <T> List<T> getClass(Class<T> clz) {
    
    
        List<T> list = new ArrayList<>();
        applicationContext.getBeansOfType(clz).forEach((a, b) -> {
    
    
            list.add(b);
        });
        return list;
    }

    public static <T> T getClassByClz(Class<T> clz) {
    
    
        return applicationContext.getBean(clz);
    }


}

4.写一个Runner类去调用这个SpringContext。

/**
 * @name : wkk
 * @description:
 * @author: Andy
 * @time: 2020/12/9 21:13
 */
@Component
public class Runner implements CommandLineRunner {
    
    

    @Override
    public void run(String... args) throws Exception {
    
    
        List<Example> list = SpringContext.getClass(Example.class);
        list.sort(new Comparator<Example>() {
    
    
            @Override
            public int compare(Example o1, Example o2) {
    
    
                return Integer.compare(o1.getOrder(),o2.getOrder());
            }
        });
        for (Example example : list) {
    
    
            example.exampleKk();
        }
    }
}

5,目录结构就是这样在这里插入图片描述
在这里插入图片描述

总结,

这个排序是实现了Ordered里的方法,然后如何排序就是按上面实现的来,把getOrder方法返回值改了,可以是任何整数,排序想变的话在Renner里面改compare方法的返回值顺序就行了,换个位置就是由大变小。

原理---->直接看源码

只有1个方法:getOrder();  2个变量:最高级(数值最小)和最低级(数值最大)。
2个变量:最高级(数值最小)和最低级(数值最大)。

1个方法:getOrder();
这个只是ordered的一个用法,还有很多东西,譬如,OrderComparator,order的比较器,具体用法等我以后用到了接着写。java无穷无尽,用什么学什么吗。

猜你喜欢

转载自blog.csdn.net/weixin_45906830/article/details/110005185
今日推荐