行业知识
SpringMVC的配置2种(本质上还是一样的,实现的接口不同)
2026-11-03 19:16:26
来源:互联网转载
���一种SpringInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer
看第一种配置
package com.xxx.config;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;public class SpringInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer { /** * //加载spring容器配置 * 加载根配置类 * @return */ @Override protected Class[] getRootConfigClasses() { return new Class[]{RootConfig.class}; } /** * 加载springmvc配置类(web容器配置类) * @return */ @Override protected Class[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } /** * 设置哪些请求归属springMVC处理 * 配置SpringMVC的映射路径(访问路径) * 配置SpringMVC拦截哪些请求(哪些请求应该交给DispatcherServlet来处理) * @return * return new String[]{"/"}; 拦截所有请求,但不拦截jsp页面 (相当于自动进入SpringMVC里面) * return new String[]{"/*"}; 表示拦截所有请求 (也相当于自动进入SpringMVC里面) * return new String[0]; html和jsp两个页面都可以访问到 */ @Override protected String[] getServletMappings() { return new String[]{"/*"}; }} WebConfig代码
package com.xxx.config;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/** * SpringMVC配置类(管理的是配置类) * -管理控制器(Servlet) * @EnableWebMvc:开启SpringMVC注解,开启后可以使用SpringMVC提供的相关注解 */@Configuration@ComponentScan("com.xxx.controller")@EnableWebMvcpublic class WebConfig implements WebMvcConfigurer { //放行静态资源 @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); }} 第二种ServletContainersInitConfig extends AbstractDispatcherServletInitializer
第二种还没配根(Spring)容器
package com.xxx.config;import org.springframework.web.context.WebApplicationContext;import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;//4.定义一个servlet容器启动的配置类,在里面加载spring的配置public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer { //加载springMVC容器配置 @Override protected WebApplicationContext createServletApplicationContext() { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(SpringMvcConfig.class); return ctx; } //设置哪些请求归属springMVC处理 @Override protected String[] getServletMappings() { return new String[]{"/"}; } //加载spring容器配置 @Override protected WebApplicationContext createRootApplicationContext() { return null; }} SpringMvcConfig代码
package com.xxx.config;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;//3.创建springmvc的配置文件,加载controller对应的bean@Configuration@ComponentScan("com.xxx.controller")public class SpringMvcConfig {}