选项 1:Spring Boot 属性(仅限 Spring Boot 1.3.0+)
从 Spring Boot 1.3.0 开始,可以使用以下属性配置此行为:
spring.mvc.dispatch-options-request=true
选项 2:自定义DispatcherServlet
DispatcherServlet
在 Spring Boot 中由DispatcherServletAutoConfiguration
. 您可以在配置类中的某个位置创建自己的DispatcherServlet
bean,而不是在自动配置中使用它:
@Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
public DispatcherServlet dispatcherServlet() {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
dispatcherServlet.setDispatchOptionsRequest(true);
return dispatcherServlet;
}
但请注意,定义您的DispatcherServlet
bean 将禁用自动配置,因此您应该手动定义在自动配置类中声明的其他 bean,即ServletRegistrationBean
for DispatcherServlet
。
选项 3:BeanPostProcessor
您可以创建BeanPostProcessor
实现,该实现将在 bean 初始化之前将dispatchOptionsRequest
属性设置为。true
Yoy 可以把它放在你的配置类中的某个地方:
@Bean
public DispatcherServletBeanPostProcessor dispatcherServletBeanPostProcessor() {
return new DispatcherServletBeanPostProcessor();
}
public static class DispatcherServletBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof DispatcherServlet) {
((DispatcherServlet) bean).setDispatchOptionsRequest(true);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
选项 4:SpringBootServletInitializer
如果你SpringBootServletInitializer
在你的应用程序中有你可以做这样的事情来启用 OPTIONS 调度:
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.getServletRegistration(DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
.setInitParameter("dispatchOptionsRequest", "true");
}
}
但是,只有当您将应用程序作为 WAR 部署到 Servlet 容器中时,这才有效,因为在使用方法SpringBootServletInitializer
运行 Spring Boot 应用程序时不会执行代码。main