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