配置Spring MVC和Tomcat

时间:2017-11-14 12:50:37

标签: spring-mvc

我们有一个现有的Spring应用程序(不是web),现在希望将一些REST端点暴露给它的功能。该要求也适用于嵌入式Tomcat。

对于战略解决方案,我们希望转向Spring Boot,短期内我们将使用Spring MVC实现端点。

我创建了一个演示Spring Boot项目,并使用它来确定Spring和Tomcat的正确依赖版本。这些是:

org.apache.tomcat.embed:tomcat-embed-core-5.23
org.apache.tomcat.embed:tomcat-embed-el-.5.23
org.apache.tomcat.embed:tomcat-embed-websocket-8.5.23
org.apache.tomcat:tomcat-annotations-api-8.5.23
org.springframework:spring-web-4.3.12.RELEASE
org.springframework:spring-webmvc-4.3.12.RELEASE
org.springframework:spring-test-4.1.0.RELEASE

在我们的主项目中,添加了代码来实例化并启动Tomcat,这似乎是成功的,如控制台所示:

Nov 14, 2017 2:32:21 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8090"]

运行应用程序的@Service主类现在实现了WebApplicationInitializeronStartup方法已经实施:

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    WebApplicationContext context = getContext();
    servletContext.addListener(new ContextLoaderListener(context));
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/*");
}

private AnnotationConfigWebApplicationContext getContext() {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.setConfigLocation("com.company.xxx");
    return context;
}

控制器已实现如下:

@RestController
@WebAppConfiguration
public class MyController {

    @RequestMapping("/")
    public String index() {
        return "Test";
    }

}

但是,主类中的onStart()方法不会被调用,即使它是一个Spring bean并且正在注入它的正确依赖项。发送get请求(http://localhost:8090/)时,Tomcat返回404 - Not Found。 任何人都可以建议缺少什么吗?

由于

0 个答案:

没有答案