Springmvc借助SimpleUrlHandlerMapping实现接口开关功能

 

  想法是好的,如何实现这一套流程呢?首先要解决以下问题。

  1、定义的接口不能被springmvc扫描到。

  2、接口定义还是要按照@RequestMaping规则方式编写,这样才能减少开发量并且能被RequestMappingHandlerMapping处理。

  3、如何自动注册url->handler到SimpleUrlHandlerMapping中去。

  对于上面需要实现的,首先要了解一些springmvc相关源码。

v  RequestMappingHandlerMapping初始化method mapping

复制代码
/**  * Scan beans in the ApplicationContext, detect and register handler methods.  * @see #isHandler(Class)  * @see #getMappingForMethod(Method, Class)  * @see #handlerMethodsInitialized(Map)  */protected void initHandlerMethods() {     if (logger.isDebugEnabled()) {         logger.debug("Looking for request mappings in application context: " + getApplicationContext());     }     String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?             BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :             getApplicationContext().getBeanNamesForType(Object.class));      for (String beanName : beanNames) {         if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {             Class<?> beanType = null;             try {                 beanType = getApplicationContext().getType(beanName);             }             catch (Throwable ex) {                 // An unresolvable bean type, probably from a lazy bean - let's ignore it.                if (logger.isDebugEnabled()) {                     logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);                 }             }             if (beanType != null && isHandler(beanType)) {                 detectHandlerMethods(beanName);             }         }     }     handlerMethodsInitialized(getHandlerMethods()); }
复制代码

   isHandler方法【判断方法是不是一个具体handler】逻辑如下

复制代码
protected boolean isHandler(Class<?> beanType) {     return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||             AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class)); }
复制代码

  所以我们定义的开关接口为了不被springmvc扫描到,直接去掉类注释上的@Controller注解和@RequestMapping注解就好了,如下。

复制代码
@Component @ResponseBody public class CommonsStateController {     @GetMapping("/url1")     public String handleUrl1()  {       return null;     }

                        
关键字:

50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信