Is using @CrossOrigin the same as overriding addCorsMapping() in Spring?

In my controller I currently added the following annotation @CrossOrigin:

    @RequestMapping(value = "/dev/test")
    public class MyController {

And also wondering the following implementation in WebConfig:

public class WebConfig implements WebMvcConfigurer {

    private String allowedRequest = "/**";
    private String allowedOrigins = "*";
    private String[] allowedMethods = {"GET", "POST", "DELETE", "OPTIONS"};

    public void addCorsMappings(final CorsRegistry registry) {

Are those two options provide the same result? And are there any difference from security standpoint (which one is more secure than the other)?

Thank you!

1 answer

  • answered 2022-05-06 15:53 dekkard

    WebMvcConfigurer#addCorsMappings(CorsRegistry) creates a global CORS configuration applied to all controllers, and @CrossOrigin allows for a more fine-grained control over it. For the case when they are used together, as stated in the javadoc of @CrossOrigin:

    The rules for combining global and local configuration are generally additive -- e.g. all global and all local origins. For those attributes where only a single value can be accepted such as allowCredentials and maxAge, the local overrides the global value.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum