First off, I've read "How to handle HTTP OPTIONS with Spring MVC?" but the answers do not seem directly applicable to Spring Boot.
It looks like I should do this:
configure the dispatcherServlet by setting its
dispatchOptionsRequest
totrue
But how to do that, given that I have no XML configs, or any variety of DispatcherServlet
initializer class in my code (mentioned by this answer)?
In a @RestController
class, I have a method like this, which currently does not get invoked.
@RequestMapping(value = "/foo", method = RequestMethod.OPTIONS)
public ResponseEntity options(HttpServletResponse response) {
log.info("OPTIONS /foo called");
response.setHeader("Allow", "HEAD,GET,PUT,OPTIONS");
return new ResponseEntity(HttpStatus.OK);
}
Spring Boot 1.2.7.RELEASE; a simple setup not very different from that in Spring REST guide.
Option 1: Spring Boot properties (Spring Boot 1.3.0+ only)
Starting with Spring Boot 1.3.0 this behavior can be configured using following property:
Option 2: Custom
DispatcherServlet
DispatcherServlet
in Spring Boot is defined byDispatcherServletAutoConfiguration
. You can create your ownDispatcherServlet
bean somewhere in your configuration classes, which will be used instead of the one in auto configuration:But be aware that defining your
DispatcherServlet
bean will disable the auto configuration, so you should manually define other beans declared in the autoconfiguration class, namely theServletRegistrationBean
forDispatcherServlet
.Option 3:
BeanPostProcessor
You can create
BeanPostProcessor
implementation which will set thedispatchOptionsRequest
attribute totrue
before the bean is initialized. Yoy can put this somewhere in your configuration classes:Option 4:
SpringBootServletInitializer
If you had
SpringBootServletInitializer
in your application you could do something like this to enable OPTIONS dispatch:That would however only work if you deployed your app as a WAR into Servlet container, as the
SpringBootServletInitializer
code is not executed when running your Spring Boot app usingmain
method.I was running into this issue with a Spring Boot 1.3.x based rest app and while diagnosing the problem I allowed my Spring Tool Suite to update to the latest version.
When I created a new test Spring Boot RestController in the updated STS, it worked as the documentation advertises under Spring 4.3. I noticed that the Maven dependency had jumped to spring boot 1.5.8 in the new test app, so I just changed the dependency for the old app to update it to spring boot 1.5.8 / spring 4.3.12. That fixed the issue and now it's working as advertised with a RequestMapping annotation specifying an interest in handling the OPTIONS requests...
... now sends the OPTIONS request to the handler.
So, if you are able to update to a later version of Spring, you should have no need to define any special configurations in order enable OPTIONS request method handling (Spring 4.3.12 / Spring Boot 1.5.8).