spring boot 中 DispatcherServlet 相关配置

 2019-11-02 21:05  阅读(2292)
文章分类:Spring boot

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);
            }
        };
    }

来源:http://ddrv.cn

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> spring boot 中 DispatcherServlet 相关配置

相关推荐