Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using static variables in Spring annotations

Tags:

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?

like image 878
RobEarl Avatar asked Jul 03 '13 09:07

RobEarl


People also ask

Can we use @value for static variables?

However, when we try to apply it to a static field, we'll find that it will still be null: @Value("${name}") private static String NAME_NULL; That's because Spring doesn't support @Value on static fields.

Can you use @autowired with static fields?

In short, no. You cannot autowire or manually wire static fields in Spring.

How can we use non static variable in static method?

The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs. This confusion is the main reason why you see this question on core Java interview as well as on core Java certifications e.g. OCAJP and OCPJP exam.

Can we Autowire static class?

What should I do not to make dao object null? I know that I could pass it as a method parameter, but that isn't very good. I'm guessing that autowired can't work on static objects, because they are created to early to autowiring mechanism isn't created yet.


2 Answers

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

like image 130
Kevin Bowersox Avatar answered Sep 21 '22 15:09

Kevin Bowersox


You can also create a bean container with roles, like:

@Component("R")
public final class RoleContainer {
  public static final String ROLE_A = "ROLE_A";
}

then on controller you can use:

@PreAuthorize("hasRole(@R.ROLE_A)")
like image 32
Алексей Виноградов Avatar answered Sep 18 '22 15:09

Алексей Виноградов