从AOP建议中设置变量

时间:2013-07-27 21:20:53

标签: aop aspectj

我使用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
  }
}

1 个答案:

答案 0 :(得分:0)

我不知道这是否是正确的方法,所以请随意发表评论。我创建了一个接口Authed及其实现AuthedImpl

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

然后我从RealEstatePropertyV1延伸AuthedImpl。我为从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);
}