[英]Spring AOP @Before advice return value
我是 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});
}
編輯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.拋出建議
public void afterThrowing(IllegalArgumentException e) throws Throwable {
}
2.退貨后的建議
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(Around Advice)
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
}
如果您在第 4 點中注意到只有 around 建議是返回對象。
您必須定義 joinPoint.proceed() 來控制攔截器何時應將控制權返回給原始方法。
在此處檢查簡單示例
編輯:我認為這可以在繼續爭論的幫助下實現
基本上,您可以使用新參數調用proceed()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.