Spring Boot — Enable CORS in Restful Web Services | Code Factory

Reference Link : Link

Donate : Link

CORS Stands for Cross-Origin Resource Sharing, As a security measure browsers will block AJAX request to the resource residing on a different origin.

CORS is a W3 Specification, which is implemented by most of the browsers and lets us request for the resource on the different domain in a safer way. (Only when the other domain sends back the response with some special Access-control headers).

In order to demonstrate how CORS works, we will be developing 2 web applications (Spring Boot RESTful Web Services and Spring Boot RESTful Web Services Client) both runs on localhost but on different ports (8080, 7070).

We will be Enable CORS in Spring Boot Restful Web Services using @CrossOrigin annotation.




Spring @CrossOrigin annotation

Spring 4.2 has introduced @CrossOrigin annotation to handle CORS, this annotation can be used in both class level and method level of the Restful Web Services. @CrossOrigin annotation has the below attributes in it.

  1. origins — This attribute sets value for Access-Control-Allow-Origin in both the pre-fligh and actual response, by default all origins are allowed.
  2. allowedHeaders — This attribute controls the value of the pre-flight response’s Access-Control-Allow-Headers header
  3. exposedHeaders — This attribute sets the value for Access-Control-Expose-Headers.
  4. maxAge — This attribute sets value for Access-Control-Max-Age response header, the default value is 1800 seconds.
  5. methods — The Methods specified here override the methods specified in @RequestMapping.If this is not defined, methods defined by @RequestMapping annotation are used.


We have used the @CrossOrigin annotation in both class and method level, So the deleteEmployee() method will have combined effect of both class and the method level @CrossOrigin annotation. It will allow origin “http://localhost:7070” and “http://localhost:9090” and exposeHeader will be “header1” and “deleteHeader”





We will be running two Tomcat server instances one on 8080 port (SpringBootRestCORS) and other on 7070 port (SpringBootRestCORSClient).

Hit http://localhost:7070/index.html

pre-flight request

actual request



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store