为了使编写没有包名的表达式成为可能:
<sec:global-method-security>
<sec:expression-handler ref="methodSecurityExpressionHandler"/>
</sec:global-method-security>
<bean id="methodSecurityExpressionHandler" class="my.example.DefaultMethodSecurityExpressionHandler"/>
然后扩展 DefaultMethodSecurityExpressionHandler:
public class DefaultMethodSecurityExpressionHandler extends org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler {
@Override
public StandardEvaluationContext createEvaluationContextInternal(final Authentication auth, final MethodInvocation mi) {
StandardEvaluationContext standardEvaluationContext = super.createEvaluationContextInternal(auth, mi);
((StandardTypeLocator) standardEvaluationContext.getTypeLocator()).registerImport("my.example");
return standardEvaluationContext;
}
}
现在创建 my.example.Roles.java :
public class Roles {
public static final String ROLE_UNAUTHENTICATED = "ROLE_UNAUTHENTICATED";
public static final String ROLE_AUTHENTICATED = "ROLE_AUTHENTICATED";
}
并在注释中不带包名的情况下引用它:
@PreAuthorize("hasRole(T(Roles).ROLE_AUTHENTICATED)")
代替:
@PreAuthorize("hasRole(T(my.example.Roles).ROLE_AUTHENTICATED)")
使其更具可读性恕我直言。现在还键入了角色。写:
@PreAuthorize("hasRole(T(Roles).ROLE_AUTHENTICATEDDDD)")
如果你写的话,你会得到不会出现的启动错误:
@PreAuthorize("hasRole('ROLE_AUTHENTICATEDDDD')")