注解实现类优先级

需求

在Spring中,我们实现了某个接口,重写了某个方法,就可以实现一些特定功能,比如说实现Mybatsi的Interceptor,重写他的intercept(Invocation invocation)方法,就可以在Mybatis执行的过程中,替换sql或者一些参数。这种实现的逻辑是,会有一些代码,将指定接口的实现类的方法,都放到一个map中,然后按顺序执行了一遍。那么现在有这样的一个场景,我们需要实现某个接口,然后这个实现类是优先级最高的,其他实现这个接口的实现类,都要被废弃掉,这种情况怎么处理呢

代码

注解类:

package com.xhfeng.studentmananger.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Order {
     int order() default 0;
}

接口:

package com.xhfeng.studentmananger.annotation;

import org.springframework.stereotype.Component;

@Component
public interface TestAnnotationService {
    void sayHello(String name);
}

实现类A:

package com.xhfeng.studentmananger.annotation.impl;

import com.xhfeng.studentmananger.annotation.Order;
import com.xhfeng.studentmananger.annotation.TestAnnotationService;
import org.springframework.stereotype.Service;

@Order(order = 20)
@Service
public class TestAnnotationServiceIChineseImpl implements TestAnnotationService {
    @Override
    public void sayHello(String name) {
        System.out.println(name+":你好!");
    }
}

实现类B:

package com.xhfeng.studentmananger.annotation.impl;

import com.xhfeng.studentmananger.annotation.Order;
import com.xhfeng.studentmananger.annotation.TestAnnotationService;
import org.springframework.stereotype.Service;

@Order(order = 30)
@Service
public class TestAnnotationServiceIEnglishImpl implements TestAnnotationService{
    public void sayHello(String name) {
        System.out.println(name+":Hello!");
    }
}

工具类:

package com.xhfeng.studentmananger.annotation;

import jdk.jfr.internal.tool.Main;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheManagerUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

@Service
public class Test {
    private static List<String> classPaths = new ArrayList<String>();
    public static int maxOrder = 0;
    public static TestAnnotationService testAnnotationService;


    @PostConstruct
    public void setAnnotationService() {
        searchClass("com.xhfeng");
    }

    public static void searchClass(String basePack) {
        //先把包名转换为路径,首先得到项目的classpath
        String classpath = Main.class.getResource("/").getPath();
        //然后把我们的包名basPach转换为路径名
        basePack = basePack.replace(".", File.separator);
        //然后把classpath和basePack合并
        String searchPath = classpath + basePack;
        doPath(new File(searchPath));
        List<Class<?>> orderList = new CopyOnWriteArrayList<>();
        //这个时候我们已经得到了指定包下所有的类的绝对路径了。我们现在利用这些绝对路径和java的反射机制得到他们的类对象
        for (String s : classPaths) {
            //把 D:\work\code\20170401\search-class\target\classes\com\baibin\search\a\A.class 这样的绝对路径转换为全类名com.baibin.search.a.A
            s = s.replace(classpath.replace("/", "\\").replaceFirst("\\\\", ""), "").replace("\\", ".").replace(".class", "");
            dealOrder(orderList, s);
        }
        try {
            testAnnotationService = (TestAnnotationService) orderList.get(0).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void dealOrder(List<Class<?>> orderList, String s) {
        try {
            Class<?> annotationServiceImpl = Class.forName(s);
            for (Class<?> anInterface : annotationServiceImpl.getInterfaces()) {
                if (TestAnnotationService.class.isAssignableFrom(anInterface)) {
                    /**
                     * 獲取該類注解
                     */
                    Order annotation = annotationServiceImpl.getAnnotation(Order.class);
                    int order = annotation.order();
                    // 獲取該類的注解,記錄排序
                    if (CollectionUtils.isEmpty(orderList)) {
                        orderList.add(annotationServiceImpl);
                        maxOrder = order;
                    } else {
                        if (order > maxOrder) {
                            orderList.clear();
                            orderList.add(annotationServiceImpl);
                        }
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static void doPath(File file) {
        if (file.isDirectory()) {//文件夹
            // 文件夹我们就递归
            File[] files = file.listFiles();
            for (File f1 : files) {
                doPath(f1);
            }
        } else {//标准文件
            // 标准文件我们就判断是否是class文件
            if (file.getName().endsWith(".class")) {
                classPaths.add(file.getPath());
            }
        }
    }
}

测试结果:
在这里插入图片描述

总结

逻辑就是,扫描全包,找到指定的接口的实现类,然后比较注解上的数字大小。也可以改造成,扫描全包,找到指定注解的类,再去判断类是否是统一接口的实现,然后比较大小,放入缓存中,供后续使用。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值