编程式启动 SpringMVC

写这个的目的是做个记录,同样也希望刚学 SpringMVC 的大学森,不用再额外下载一个 Tomcat 到本地,每次启动应用都要打包成 war 放到 Tomcat 里(即便借助IDE会让这个流程变得简单)。

首先,需要知道的是:

  1. SpringMVC的Servlet配置是 Java 配置,Servlet 容器启动时会自动需要相关的Servlet初始化配置类进行配置

  2. Spring Boot 也使用内嵌的Servlet容器(比如Tomcat),但是 Spring Boot 的配置方式跟 Spring MVC 的不一样

首先,需要知道的是,Tomcat、Jetty 还是 Undertow,它们都有一套自己的 HttpHandle定义,Servlet 只是他们的特殊实现而已,也就是说,你不适用 Servlet API,你也可以用它们来开发 WEB 应用。

Tomcat、Jetty 还是 Undertow 都可以Java编程时显示启动的,但是 undertow 是它们中用起来最方便的一个,所以只介绍它,就足够了。

Undertow

Maven GAV:

    <dependency>
      <groupId>io.undertow</groupId>
      <artifactId>undertow-core</artifactId>
      <version>2.1.0.Final</version>
    </dependency>

    <dependency>
      <groupId>io.undertow</groupId>
      <artifactId>undertow-servlet</artifactId>
      <version>2.1.0.Final</version>
    </dependency>
复制代码

main method:

    public static void main(String[] args) throws ServletException {
        
        Set<Class<?>> handlesTypes = new HashSet<>();
        // WebInitializer 类是你的 WebApplicationInitializer 实现类
        // 在 SpringMVC 中,其实就是你继承 AbstractAnnotationConfigDispatcherServletInitializer 的类
        handlesTypes.add(WebInitializer.class);  

        // SpringServletContainerInitializer 是 ServletContainerInitializer 实现类
        ServletContainerInitializerInfo info = new ServletContainerInitializerInfo(
            SpringServletContainerInitializer.class, handlesTypes);


        // 下面的就是 Undertow 的配置流程了
        DeploymentInfo  deploymentInfo = Servlets.deployment()
            .setDeploymentName("demo-server")
            .setClassLoader(
                        DemoApplication.class.getClassLoader())
            .setContextPath("/")
            .addServletContainerInitializer(info);

        ServletContainer container = Servlets.defaultContainer();
        DeploymentManager manager = container.addDeployment(deploymentInfo);
        manager.deploy();
       
    
        Undertow server = Undertow
            .builder()
            .addHttpListener(8080, "localhost")
            // HttpHandler 参数类型,你可以自由实现,可以看出 Servlet 容器只是特殊的 HttpHandler
            .setHandler(manager.start()) 
            .build();
        server.start();
    }
复制代码

启动日志如下:

image.png

OK, dispatcher Servlet 能初始化成功,就代表 Spring 容器启动成功了

发个请求测试下

image.png

成功!

猜你喜欢

转载自juejin.im/post/7019706418596937758