SpringMVC,使用两个上下文和两个调度程序用于Rest Service和普通内容

时间:2016-03-24 04:29:53

标签: spring spring-mvc

在我的SpringMVC项目配置中,我有一个RootContextConfiguration和其他两个上下文配置文件,用于休息服务和正常请求; RestServletContextConfigurationWebServletContextConfiguration

而且,我正在引导应用程序,如下面的代码所示。

public class Bootstrap implements WebApplicationInitializer
{

    @Override
    public void onStartup(ServletContext container) throws ServletException
    {
        container.getServletRegistration("default").addMapping("/resource/*");

        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(RootContextConfiguration.class);
        container.addListener(new ContextLoaderListener(rootContext));

        AnnotationConfigWebApplicationContext restContext = new AnnotationConfigWebApplicationContext();
        restContext.register(RestServletContextConfiguration.class);
        DispatcherServlet restServlet = new DispatcherServlet(restContext);
        restServlet.setDispatchOptionsRequest(true);
        ServletRegistration.Dynamic springRestDispatcher = container.addServlet("springRestDispatcher", restServlet);
        springRestDispatcher.setLoadOnStartup(1);
        springRestDispatcher.addMapping("/api/*");

        AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
        webContext.register(WebServletContextConfiguration.class);
        DispatcherServlet webServlet = new DispatcherServlet(webContext);
        ServletRegistration.Dynamic springWebDispatcher = container.addServlet("springWebDispatcher", webServlet );
        springWebDispatcher.setLoadOnStartup(2);
        springWebDispatcher.setMultipartConfig(new MultipartConfigElement(null, 20_971_520L, 41_943_040L, 512_000));
        springWebDispatcher.addMapping("/*");
    }
}

我需要 / api / cars 来解析

@RestController
@RequestMapping("/cars")
class CarRestController{}

/ cars 解析为

@Controller
@RequestMapping("/cars")
class CarController{}

但是,由于模糊映射,部署失败。如果我将CarRestController的映射更改为@RequestMapping('/api/cars'),那么我可以使用路径 / api / api / cars 访问该控制器(请注意双 api 前缀)。但我想要的是能够使用 / api / cars 访问CarRestController

我应该怎样做才能实现目标?非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

为什么你不在你的方法上放置映射@RequestMapping?

例如

@RestController
public class YourClass {
@RequestMapping("/car")
public String yourMethod() {  }
}