将一个请求重定向到处理程序中的许多内部请求。反射+自定义注释

时间:2018-10-01 10:54:25

标签: java spring design-patterns reflection annotations

我有一个控制器方法(在实际项目中是SOAP服务的方法):

@Slf4j
@RestController
public class ControllerDispatcher {

@PostMapping("request")
public void sendGenericRequest(@RequestBody MainRequest mainRequest) {}
}

通过这种方法,我收到了MainRequest类。此类是wrapper(ExternalRequest)。它包含3个内部请求:

@Data
public class MainRequest {

    enum Type {FIRST, SECOND, LAST}

    private Type type;  //type of request
    private String request; //internal request in String format.
}

我需要像spring dispather-servlet(类似的东西)这样的逻辑,并且已经捕获了将请求扔到所需方法中的请求。我使用自定义注释创建了Handler

@InternalHandlerAnnotation
public class InternalRequestHandler {

    public void firstInternalrequest(FirstInternalRequest firstInternalRequest){

    }

    public void secondInternalrequest(SecondInternalRequest secondInternalRequest){

    }

    public void lastInternalrequest(LastInternalRequest lastInternalRequest){

    }
}

我想让MainRequest的haddle InternalRequestMainRequest解组到类并重定向到具体的hadler方法。

我可以收到3个内部请求:

@Data
public class FirstInternalRequest {
    private Long id;
    private String name;
    private int age;
}

@Data
public class SecondInternalRequest {
    private Long id;
    private String description;
}

@Data
public class LastInternalRequest {
    private Long id;
    private String hz;
    private int hz2;
}

现在,我需要一种机制来检测内部请求并将其重定向到处理程序类的方法。我有解决方案:

@Component
public class HandlersResolver {
    private final ApplicationContext context;
    private Map<String, Object> beansWithAnnotation;

    public HandlersResolver(ApplicationContext context) {
        this.context = context;
    }

    @PostConstruct
    public void init() {
        beansWithAnnotation = context.getBeansWithAnnotation(InternalHandlerAnnotation.class);
        initHandler();
    }

    private void initHandler() {
        for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
            Annotation[] annotations = entry.getValue().getClass().getAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation instanceof InternalHandlerAnnotation) {
                    Object beanWithMyAnnotation = entry.getValue();
                    Method[] declaredMethods = beanWithMyAnnotation.getClass().getDeclaredMethods();
                    for (Method declaredMethod : declaredMethods) {
                     Parameter[] parameters = declaredMethod.getParameters();
                     Parameter parameter = parameters[0];
                     Class<?> type = parameter.getType();
                     //convert String to type   
                }
                }
            }

        }
    }
}

我可以使用注释来检测bean。获取方法,在每个方法中获取参数。但是接下来如何做不明白。如何在处理程序中将String从MainRequets转换为这种类型和cal方法?

0 个答案:

没有答案