SpringBoot应用中扫描自定义注解
使用背景
需要通过业务键值来调用不同的类里的不同方法
重点描述
引入依赖
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.10.2</version>
</dependency>
扫描注解
@Configuration
public class BusiIDConfig {
private Map<String, BusiMethodInfo> methodInfoMap = new HashMap<>();
@PostConstruct()
public void init(){
String basePackage = "com.wywtime.comb";
Reflections f = new Reflections(basePackage);
Set<Class<?>> set = f.getTypesAnnotatedWith(DataComb.class);
for (Class<?> c : set) {
for(Method method:ReflectionUtils.getMethods(c, ReflectionUtilsPredicates.withAnnotation(BusiID.class))){
BusiID busiID = method.getAnnotation(BusiID.class);
methodInfoMap.put(busiID.name(),new BusiMethodInfo(c,method));
}
}
}
public Map<String, BusiMethodInfo> getMethodInfoMap() {
return methodInfoMap;
}
}
方法调用
public class BusiPOExecutor {
public static void doMethod(String busiId) throws Exception {
BusiMethodInfo methodInfo = AppCtxUtil.getBean(BusiIDConfig.class).getMethodInfoMap().get(busiId);
methodInfo.getMethod().invoke(AppCtxUtil.getBean(methodInfo.getClazz()));
}
}
源码
本文来自博客园,作者:白首码农,转载请注明原文链接:https://www.cnblogs.com/bsmn/p/16436185.html