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()));
    }
}

源码

bsmn-springboot-lab.zip

posted on 2022-07-01 22:55  白首码农  阅读(1331)  评论(0编辑  收藏  举报