设计模式:策略模式(根据参数,调用不同的service接口)

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<String, Class<? extends DataProvider>> providers = Maps.newConcurrentMap();

@SuppressWarnings("unchecked")
@PostConstruct
public void init() {
Set<Class<?>> 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();
}

  

 

posted @ 2019-05-31 14:21  蔡徐坤1987  阅读(8388)  评论(0编辑  收藏  举报