2013-07-27 69 views
1

我使用AOP建議將User對象轉換爲Owner對象。轉換是在建議中完成的,但我想將該對象傳遞給調用者。從AOP建議中設置變量

@Aspect 
public class UserAuthAspect { 
    @Inject 
    private OwnerDao ownerDao; 

    @Pointcut("@annotation(com.google.api.server.spi.config.ApiMethod)") 
    public void annotatedWithApiMethod() { 
    } 

    @Pointcut("execution(* *.*(.., com.google.appengine.api.users.User)) && args(.., user)") 
    public void allMethodsWithUserParameter(User user) { 
    } 

    @Before("annotatedWithApiMethod() && allMethodsWithUserParameter(user)") 
    public void checkUserLoggedIn(com.google.appengine.api.users.User user) 
      throws UnauthorizedException { 
     if (user == null) { 
      throw new UnauthorizedException("Must log in"); 
     } 
     Owner owner = ownerDao.readByUser(user); 
    } 
} 

一類以建議的方法:

public class RealEstatePropertyV1 { 
    @ApiMethod(name = "create", path = "properties", httpMethod = HttpMethod.POST) 
    public void create(RealEstateProperty property, User user) throws Exception { 
     Owner owner = the value set by the advice 
    } 
} 

回答

0

我不知道,如果是做正確的方式,可以隨意發表評論。我創建了一個接口Authed及其實現AuthedImpl

public interface Authed { 
    void setOwner(Owner owner); 
} 

然後我做了RealEstatePropertyV1AuthedImpl延伸。我爲從AuthedImpl延伸的所有類添加了切入點,並且還更改了切入點,以便可以訪問目標。

@Pointcut("execution(* *..AuthedImpl+.*(..))") 
public void extendsAuthedImpl() { 
} 

@Pointcut("execution(* *.*(.., com.google.appengine.api.users.User)) && args(.., user) && target(callee)") 
public void allMethodsWithUserParameter(User user, Authed callee) { 
} 

最後建議使用所有切入點:

@Before("annotatedWithApiMethod() && allMethodsWithUserParameter(user, callee) && extendsAuthedImpl()") 
public void checkUserLoggedIn(com.google.appengine.api.users.User user, 
     Authed callee) throws UnauthorizedException { 
    System.out.println(callee.getClass()); 
    if (user == null) { 
     throw new UnauthorizedException("Must log in"); 
    } 
    Owner owner = ownerDao.readByUser(user); 
    callee.setOwner(owner); 
} 
+0

也許我錯過了一些東西,但如果'RealEstatePropertyV1'(您的正常計劃的一部分)延伸'AuthedImpl'(您方面的一部分),沒有按它會在程序和方面之間創建依賴關係嗎?只有在方面方法或正常程序中才需要'Owner'?可能它只是讓我困惑的名字:它是* UserAuthAspect *還是*注入者*方面? – Beryllium

+0

你是對的,我介紹了我的程序和方面之間的依賴關係。我需要正常程序中的'Owner'。基本上我希望我的方面將'User'轉換爲'Owner',然後將'Owner'傳遞迴正常的程序。 – Sydney

+0

實際上'AuthImpl'不是方面的一部分。該方面只是'UserAuthAspect'。 – Sydney