2009-06-19 142 views
3

是否有可能做到以下幾點: 我可以使用AOP註釋在春季注入代碼嗎?

public void doStuff(@RequirePrivilege("foo") User user) { 
    // ... 
} 

並使其有效地運行,好像它是下面那樣?

public void doStuff(User user) { 
    if(!user.hasPrivilege("foo")) 
     throw new UserHasInsufficientPrivileges(); // this is a RuntimeException 
    // ... 
} 

我知道Spring有各種各樣的AOP支持,但我能找到的最好的是AOP代碼,它被註釋以便在特定方法之前或之後執行。我想做相反的事情並且註釋應該改變的代碼。

最終,我只能在方法內執行上面的檢查,但是處理註釋的方式提供了額外的文檔,這使得用戶需要特定的權限而無需保持文檔與代碼同步。

回答

1

你可以看看使用AspectJ來做到這一點,因爲它會匹配註釋。然後,您可以使用周圍方面來決定用戶是否符合使用此方法的要求。

Spring允許您使用AspectJ,如果可能的話,您不會在運行時執行此操作,但在編譯時會出現這種情況,因爲無論何時您啓動應用。但是,如果你必須在運行時執行它,那麼這是可行的,對我來說,我嘗試儘可能地使用編譯時。

你可能想看看的AspectJ在行動(http://www.manning.com/laddad2/),但這裏有一個例子從那裏: 簽名模式:

* *(@RequestParam 
(@Sensitive *)) 

說明

*Any method with one parameter marked with the @RequestParam annotations and the parameter’s type is marked with the @Sensitive annotation.* 

void create(@RequestParam 
MedicalRecord mr), assuming 
MedicalRecord carries the 
@Sensitive annotation. 
1

我確定您的「權限不足」示例可以使用Spring AOP來完成,因爲這就是Spring Security的工作原理。你可以用周圍的建議和AspectJ做一些非常複雜的事情。