Spring MVC自动装配RequestMappingHandlerMapping

5

我正在尝试在我的Spring MVC控制器中自动装配org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping,以便获取所有URL映射并在UI上显示它们,但没有成功。出现了缺少bean的错误:

 org.springframework.beans.factory.BeanCreationException: Could    not autowire field: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping web.controller.WorkController.handlerMapping; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我的web.xml:

<display-name>Spring MVC Application</display-name>

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>


<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/root-context.xml</param-value>
</context-param>

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

我的mvc-dispatcher-servlet.xml文件:

 <context:annotation-config/>
    <context:component-scan base-package="web.controller"/>
             <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

我的root-context.xml文件:

<bean id="helloBean" class="web.beans.HelloBean"/>

Java控制器:
package web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import web.beans.HelloBean;

import java.util.List;

@Controller
public class WorkController {

    @Autowired RequestMappingHandlerMapping handlerMapping;
    @Autowired private HelloBean helloBean;
    @Autowired private ApplicationContext applicationContext;

    @RequestMapping(value = "/index")
    public String index() {
        return "index";
    }
}
4个回答

7

在自动装配之前,您应该启动RequestMappingHandlerMapping bean。

有两种方法:

  1. 在Spring XML配置中,例如hello bean
<bean name="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<!-- add your properties here property name="..." value="..."></property-->
</bean>
  1. Or using

    @Configuration

    @Configuration 
    @ComponentScan("your.package") 
    @EnableWebMvc   
    public class AppConfig {  
    ...
        @Bean
        public RequestMappingHandlerMapping requestMappingHandlerMapping() {
           RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping();
           // add properties here
           return mapping;
        }
    ...
    } 
    

3
尝试获取所有请求的 urls,下面的代码可能对你有用。
ServletContext servletContext = request.getSession().getServletContext();
WebApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
Map<String, HandlerMapping> allRequestMappings = BeanFactoryUtils.beansOfTypeIncludingAncestors(appContext, HandlerMapping.class, true, false);
for (HandlerMapping handlerMapping : allRequestMappings.values()) {
    if (handlerMapping instanceof RequestMappingHandlerMapping) {
          RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) handlerMapping;
          Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
          for (Map.Entry<RequestMappingInfo, HandlerMethod> requestMappingInfoHandlerMethodEntry : handlerMethods.entrySet()) {
             RequestMappingInfo requestMappingInfo = requestMappingInfoHandlerMethodEntry.getKey();
             PatternsRequestCondition patternsCondition = requestMappingInfo.getPatternsCondition();
             String requestUrl = SetUtils.first(patternsCondition.getPatterns());
             System.out.println(requestUrl);
          }
    }
}

坦率地说,Java反射是获取所有请求URL的关键点。如果您深入研究spring-mvc源代码,您将发现HandlerMapping接口的实现类,例如:
AbstractControllerUrlHandlerMapping, AbstractDetectingUrlHandlerMapping,
AbstractHandlerMapping, AbstractHandlerMethodMapping,
AbstractUrlHandlerMapping, BeanNameUrlHandlerMapping, 
ControllerBeanNameHandlerMapping, ControllerClassNameHandlerMapping,
DefaultAnnotationHandlerMapping, RequestMappingHandlerMapping,
RequestMappingInfoHandlerMapping, SimpleUrlHandlerMapping 

SetUtils.first()是什么? - NickJ
1
@NickJ 可以将其视为final Set<String> patterns = patternsCondition.getPatterns(); String requestUrl = patterns.stream().findFirst().orElse(StringUtils.EMPTY); - Scolytus

2
  • 我尝试在我的主类中添加"@EnableWebFlux",并且它有效(在我的情况下)。
  • 所以我认为也许"EnableWebMvc"也有效果..
  • 对我来说它很好用,请不要↓我 :)
@EnableWebFlux(for webflux)
@EnableWebMvc(for commvc)
@SpringBootApplication
public class InstoreApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(InstoreApplication.class)......
    }
}

请参考以下链接:https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-config-enable - Santonio

0

您可以在 *.properties 文件中添加以下内容:

# Log restful end points
logging.level.web=TRACE
logging.level.org.springframework.web=TRACE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接