Search code examples
javaspringspring-securityspring-annotations

Using static variables in Spring annotations


I'm using spring's PreAuthorize annotation as follows:

@PreAuthorize("hasRole('role')");

However, I already have 'role' defined as a static String on another class. If I try to use this value:

@PreAuthorize("hasRole(OtherClass.ROLE)");

I get an error:

org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 14): Field or property 'OtherClass' cannot be found on object of type 'org.springframework.security.access.expression.method.MethodSecurityExpressionRoot'

Is there a way to access static variables like this with a PreAuthorize annotation?


Solution

  • Try the following which uses Spring Expression Language to evaluate the type:

    @PreAuthorize("hasRole(T(fully.qualified.OtherClass).ROLE)");
    

    Be sure to specify the fully qualified class name.

    Documentation