利用反射注册Controller

利用反射注册Controller代码

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

public class ApiRegister {
    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @GetMapping("register")
    public Object register() throws NoSuchMethodException {

        PatternsRequestCondition patternsRequestCondition = new PatternsRequestCondition("/test");

        RequestMethodsRequestCondition methodsRequestCondition = new RequestMethodsRequestCondition(RequestMethod.valueOf("GET"));
        RequestMappingInfo mappingInfo = new RequestMappingInfo(patternsRequestCondition,methodsRequestCondition,null,null,null,null,null);

        Method targetMethod = ApiRegister.class.getDeclaredMethod("execute", HttpServletRequest.class);
        requestMappingHandlerMapping.registerMapping(mappingInfo,this, targetMethod);


        return "succeed";
    }

    public ResponseEntity execute(HttpServletRequest request){
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body("反射注册");

    }
}

你可能感兴趣的:(利用反射注册Controller)