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>dispatcherservlet-name>  
  <servlet-class>  
    org.springframework.web.servlet.DispatcherServlet  
  servlet-class>  
  <init-param>  
    <param-name>contextConfigLocationparam-name>  
    <param-value>/WEB-INF/spring/dispatcher-config.xmlparam-value>  
  init-param>  
  <load-on-startup>1load-on-startup>  
servlet>  

<servlet-mapping>  
  <servlet-name>dispatcherservlet-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,java)