设计模式:策略模式(根据参数,调用不同的service接口)
阅读原文时间:2023年07月09日阅读:1

1.定义类容器providers,当spring加载时@PostConstruct(类似构造方法),会先执行init() ; 在init()中,反射"cn.jdk18"的所有带自定义注解@ProviderName的java文件,并且遍历的类要满足被DataProvider继承关系,将满足条件的类放到providers容器中

2.前端url 访问 {basePath}/jdbc 或 {basePath}/kylin  即可调用不用的service

ClassByTypeServiceImpl

@Service
public class ClassByTypeServiceImpl implements ClassByTypeService {

private Map> providers = Maps.newConcurrentMap();

@SuppressWarnings("unchecked")
@PostConstruct
public void init() {
Set> setClass = new Reflections("cn.jdk18").getTypesAnnotatedWith(ProviderName.class);
for (Class class1 : setClass) {
if (!class1.isAssignableFrom(DataProvider.class)) {
System.out.println(class1.getName());
ProviderName providerName = class1.getAnnotation(ProviderName.class);
providers.put(providerName.name(), (Class) class1);
} else {
System.out.println("未被继承:" + class1.getName());
}
}
}

public Class getClassByType(String type) {
return providers.get(type);
}

}

ClassByTypeService

public interface ClassByTypeService {
Class getClassByType(String type);
}

ProviderName

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ProviderName {
String name();
}

JDBCDataProvider

@ProviderName(name = "jdbc")
public class JDBCDataProvider extends DataProvider{
public void helloWorld(){}
}

KylinDataProvider

@ProviderName(name = "kylin")
public class KylinDataProvider extends DataProvider{
public void helloWorld(){}
}

UserController

@RequestMapping("/getClassByType/{type}")
public String getClassByType(@PathVariable String type){
return "saySomething:"+classByTypeService.getClassByType(type).getName();
}