1

我使用AOP建议将User对象转换为Owner对象。转换是在建议中完成的,但我想将该Owner对象传递给调用者。

@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
  }
}
4

1 回答 1

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);
}
于 2013-07-28T12:05:50.523 回答