Logo InterviewVault

Welcome back, Sujit Kumar Mishra

SKM

Revision Mode

Document technical questions and best-practice answers.

Cancel

How can we enable the CrossOrigin resource sharing in SpringBoot? Which builtin method overrides the CrossOrigin resource sharing feature and which annotation mostly we used in this case?

To enable CORS in Spring Boot, follow these simple steps:


1: Use the @CrossOrigin Annotation:

The easiest way to enable CORS for a specific controller or method is to add the @CrossOrigin annotation.

Example:

@CrossOrigin
@GetMapping("/example")
public String example() {
  return "Hello";
}


2: Override the addCorsMappings Method:

For global CORS configuration, override the addCorsMappings method in a configuration class that implements WebMvcConfigurer.

Example:

@Configuration
public class WebConfig implements WebMvcConfigurer {
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedOrigins("*");
  }
}


Summary (Easy to Remember):

1: Use @CrossOrigin annotation for quick enablement.

2: Override addCorsMappings for global settings.

3: The most used annotation is @CrossOrigin.


Tip:

Remember: @CrossOrigin = Enable CORS easily in Spring Boot!

Ready for commit