我的应用程序中有两种方法,它们使用相同的请求映射和不同的 (http) 方法
@RequestMapping(value = "/method/{key}", method = RequestMethod.GET)
public void method1(<parameters>) throws IOException {
// ...
}
@RequestMapping(value = "/method/{key}", method = RequestMethod.PUT)
public void method2(<parameters>) throws IOException {
// ...
}
只要两种方法都在同一个 Controller 中定义,这种方法就可以完美工作,但是,由于我正在使用的公司框架,我需要它们位于两个不同的 Controller 中,并且当我启动我的应用程序,收到以下错误:
Caused by: java.lang.IllegalStateException: Cannot map handler 'MyController#0' to URL path [/method/{key}]: There is already handler of type [class OtherController$$EnhancerByCGLIB$$54a955d] mapped. at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:390) at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:362) at org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.detectHandlers(AbstractDetectingUrlHandlerMapping.java:82) at org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping.initApplicationContext(AbstractDetectingUrlHandlerMapping.java:58) at org.springframework.context.support.ApplicationObjectSupport.initApplicationContext(ApplicationObjectSupport.java:119) at org.springframework.web.context.support.WebApplicationObjectSupport.initApplicationContext(WebApplicationObjectSupport.java:72) at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:73) at org.springframework.context.support.ApplicationContextAwareProcessor.invokeAwareInterfaces(ApplicationContextAwareProcessor.java:109) at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:88) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:393) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1415) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:518) ... 25 more
是否可以在不同的 Controller 中定义它们,或者我应该考虑一些(可怕的)解决方法(例如重命名其中一个 URL)?
最佳答案
从 Spring 3.1 开始它应该可以正常工作(如果启用了新的映射实现 - 如果使用 <mvc:annotation-driven>
或 @EnableWebMvc
并且不手动声明任何 HandlerMapping
,则默认情况下启用它)。
在旧版本的 Spring 中,您必须将这些方法放入同一个 Controller 中。
关于java - 是否可以使用不同的方法将相同的映射映射到两个不同的 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14528694/