spring boot 中 DispatcherServlet 相关配置

1. 自定义配置mapping映射路径

可以在application.properties加入配置,如:

server.servlet-path=/api/*

也可以注入一个新的ServletRegistrationBean用于映射新的url:

//自动注入spring boot默认的上传配置
@Autowired
private MultipartConfigElement multipartConfigElement;
@Autowired
private DispatcherServlet dispatcherServlet;
@Bean
public ServletRegistrationBean apiServlet() {
    ServletRegistrationBean bean = new ServletRegistrationBean(dispatcherServlet);
    //注入上传配置到自己注册的ServletRegistrationBean
    bean.addUrlMappings("/api/*");
    bean.setMultipartConfig(multipartConfigElement);
    bean.setName("apiServlet");
    return bean;
}

在spring boot中配置多个DispatcherServlet 文章传送门

2. 自定义的web.xml配置

java配置

public class MyWebAppInitializer implements WebApplicationInitializer {  

   @Override  
   public void onStartup(ServletContext container) {  
      XmlWebApplicationContext appContext = new XmlWebApplicationContext();  
      appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");  

      ServletRegistration.Dynamic dispatcher =  
       container.addServlet("dispatcher", new DispatcherServlet(appContext));  
      dispatcher.setLoadOnStartup(1);  
      dispatcher.addMapping("/");  
   }  

}  

代替Xml代码

<servlet>  
  <servlet-name>dispatcher</servlet-name>  
  <servlet-class>  
    org.springframework.web.servlet.DispatcherServlet  
  </servlet-class>  
  <init-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>  
  </init-param>  
  <load-on-startup>1</load-on-startup>  
</servlet>  

<servlet-mapping>  
  <servlet-name>dispatcher</servlet-name>  
  <url-pattern>/</url-pattern>  
</servlet-mapping>  

3. 只配置 DispatcherServlet的加载

可以在application.properties加入配置,如:

spring.mvc.servlet.load-on-startup=1

也可以在spring boot的启动类中加入下面代码

@Bean
public static BeanFactoryPostProcessor beanFactoryPostProcessor() {
    return new BeanFactoryPostProcessor() {

        @Override
        public void postProcessBeanFactory(
                ConfigurableListableBeanFactory beanFactory) throws BeansException {
            BeanDefinition bean = beanFactory.getBeanDefinition(
                    DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);

            bean.getPropertyValues().add("loadOnStartup", 1);
        }
    };
}
    原文作者:Spring Boot
    原文地址: https://blog.csdn.net/m0_37893932/article/details/79665148
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞