@CrossOrigin in Spring: What It Is and How to Use It
@CrossOrigin is a Spring annotation that enables cross-origin resource sharing (CORS) on REST controllers or methods. It allows your backend to accept requests from different domains, which is essential for web apps calling APIs from other origins.How It Works
Imagine your web app is like a shop that only lets customers from the same street enter. Browsers have a security rule called the Same-Origin Policy that blocks web pages from making requests to a different domain (or origin) than the one that served the page. This is to protect users from malicious sites.
@CrossOrigin acts like a special permission slip that your backend server gives to browsers, saying "It's okay to let visitors from these other streets (origins) come in and ask for data." When you add @CrossOrigin to your Spring controller or method, Spring adds the necessary HTTP headers to allow these cross-origin requests.
This way, your frontend running on one domain can safely communicate with your backend on another domain without the browser blocking the request.
Example
This example shows how to allow cross-origin requests from http://example.com to a REST controller method.
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class GreetingController { @CrossOrigin(origins = "http://example.com") @GetMapping("/greet") public String greet() { return "Hello from Spring!"; } }
When to Use
Use @CrossOrigin when your frontend and backend are hosted on different domains or ports, and you want the frontend to call backend APIs directly from the browser.
Common real-world cases include:
- A React or Angular app running on
localhost:3000calling a Spring backend onlocalhost:8080during development. - A web app hosted on
www.myfrontend.comcalling APIs onapi.mybackend.com. - Allowing third-party websites to access your public APIs safely.
Without @CrossOrigin, browsers block these cross-domain calls, causing errors and failed requests.
Key Points
@CrossOriginenables CORS by adding HTTP headers to responses.- You can specify allowed origins, methods, headers, and credentials.
- It can be applied at class or method level for fine control.
- Helps frontend apps communicate with backend APIs across different domains.
- Essential for modern web apps with separate frontend and backend deployments.
Key Takeaways
@CrossOrigin allows your Spring backend to accept requests from different domains by enabling CORS.@CrossOrigin parameters.