爲了能夠寫出表達式,而不包名:
<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')")
偉大的作品,謝謝! – RobEarl
@RobEarl真棒很高興我能幫到你。我也學到了一些東西。 –
Works,但它仍然是一個解釋的字符串,所以當您重構例如Eclipse時,它不會被Eclipse「看到」。我猜的名字。 – yglodt