Global CORS configuration
As an alternative to fine-grained annotation-based configuration, you can also define some global CORS configuration as well. This is similar to using a Filter
based solution, but can be declared within Spring MVC and combined with fine-grained @CrossOrigin
configuration. By default all origins and GET
, HEAD
and POST
methods are allowed.
src/main/java/hello/GreetingController.java
@GetMapping("/greeting-javaconfig")
public Greeting greetingWithJavaconfig(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
src/main/java/hello/Application.java
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
}
};
}
You can easily change any properties (like the allowedOrigins
one in the example), as well as only apply this CORS configuration to a specific path pattern. Global and controller level CORS configurations can also be combined.