我使用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
}
}
答案 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);
}