需求
在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());
}
}
}
}
测试结果:
总结
逻辑就是,扫描全包,找到指定的接口的实现类,然后比较注解上的数字大小。也可以改造成,扫描全包,找到指定注解的类,再去判断类是否是统一接口的实现,然后比较大小,放入缓存中,供后续使用。