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
@SuppressWarnings("unchecked")
@PostConstruct
public void init() {
Set
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();
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章