用 WebApplicationInitializer 接入 Spring MVC

This commit is contained in:
2026-10-21 21:01:13 +08:00
parent 187bf89256
commit 2e9f3f0684
3 changed files with 42 additions and 0 deletions
@@ -0,0 +1,20 @@
package com.ycjy;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class MyMvcAppInit implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(servletContext);
context.register(MySystemConfig.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
dispatcher.addMapping("/");
}
}
@@ -0,0 +1,9 @@
package com.ycjy;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.ycjy.controller")
public class MySystemConfig {
}
@@ -0,0 +1,13 @@
package com.ycjy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController1 {
@RequestMapping("/m1")
public void m1(){
System.out.println("我是m1=====");
}
}