Search code examples
javaspringspring-mvccorsspring-annotations

How can I use a constant to enter multiple @CrossOrigins?


I have a @CrossOrigin annotation on several of my controllers. I'd like to be able to set a static final somewhere and have all of them refer to it. Something like:

public static final String[] ORIGINS = {"domain1","domain2"};
...
@CrossOrigin(origins = ORIGINS)

However, I clearly have some syntax off.

Solution For those who are interested in doing the same thing, here's what I did:

@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@CrossOrigin(origins = {
        "domain1",
        "domain2"
})
@Controller
@interface CORSPermittedController {
}

That allows me to annotate all my controllers with @CORSPermittedController


Solution

  • Unfortunately, you can't do that with Java syntax. Attribute values must be compile constants (primitive, String literals, or arrays of these types).

    But you could write a bean post processor which is responsible for putting this annotation over a class at runtime by using javassist.