我是Spring AOP的新手,我想知道是否可以将@Before
的值返回给方法并在其中使用此变量,例如:
@Before("@annotation(CheckUserReservationPermission) && args(username,idReservation)")
public Reservation userCreationAdvice(ProceedingJoinPoint pjp, String username, Integer idReservation) throws Throwable {
Reservation reservation = reservationServices.findById(idReservation);
if (!reservation.getUser().getUsername().equals(username))
throw new PermissionException("You can't delete the reservation with id: " + idReservation);
return reservation;
}
和我的方法:
@Override
@CheckUserReservationPermission
public void deleteReservationById(String username, Integer idReservation) throws QueryException {
synchronized(ReservationsSchedulerServicesImpl.class){
databaseReservationServices.deleteReservationById(username, reservation);
}
}
有没有办法做到这一点?否则我必须重复查询。 感谢
更新 :使用@Around
我可能有此代码,但如何将变量检索到deleteReservationById
方法?
@Around("@annotation(CheckUserReservationPermission) && args(username,idReservation)")
public Object userCreationAdvice(ProceedingJoinPoint pjp, String username, Integer idReservation) throws Throwable {
Reservation reservation = reservationServices.findById(idReservation);
if (!reservation.getUser().getUsername().equals(username))
throw new PermissionException("You can't delete the reservation with id: " + idReservation);
return pjp.proceed(new Object[] {reservation});
}
答案 0 :(得分:0)
编辑2:
建议
@Around("@annotation(CheckUserReservationPermission) && args(username,idReservation)")
public Object userCreationAdvice(ProceedingJoinPoint pjp, DeleteByIdRequest req) throws Throwable {
Reservation reservation = reservationServices.findById(idReservation);
if (!reservation.getUser().getUsername().equals(username)) {
throw new PermissionException("You can't delete the reservation with id: " + idReservation);}
req.setReservation(reservation);
return pjp.proceed(new Object[] {req});
}
2。 新请求POJO
class DeleteByIdRequest {
Reservation reservation;
String username;
Integer idReservation;
}
3.目标方法
@Override
@CheckUserReservationPermission
public void deleteReservationById(DeleteByIdRequest request) throws QueryException {
synchronized(ReservationsSchedulerServicesImpl.class){
databaseReservationServices.deleteReservationById(username, reservation);
}
}
查看此建议的界面,
检查他们返回的内容。
1.ThrowsAdvice
public void afterThrowing(IllegalArgumentException e) throws Throwable {
}
2.AfterReturningAdvice
public void afterReturning(Object returnValue, Method method,
Object[] args, Object target) throws Throwable {
}
3.MethodBeforeAdvice
public void before(Method method, Object[] args, Object target)
throws Throwable {
}
4.MethodInterceptor(围绕建议)
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
}
如果您在第4点注意仅周围建议返回对象。
你必须定义joinPoint.proceed()来控制拦截器何时将控件返回到原始方法。
检查简单示例here
修改强>
我认为这可以在proceeding with arguments的帮助下实现
基本上你可以用新参数调用proceed()。