如何访问建议方法的返回Object实例

时间:2011-04-15 15:31:44

标签: java spring aop aspectj

我正在使用spring AOP来建议我的服务方法,尤其是返回对象的方法,我想在建议处理过程中访问该对象。

我的配置工作正常,没有问题。

这是adviced方法的签名,方法根据方法参数中的数据返回一个新实例,因此参数不可用

@Traceable(ETraceableMessages.SAUVER_APPORTEUR)
public ElementNiveauUn save(ElementNiveauUn apporteur) throws ATPBusinessException {
    String identifiant = instanceService.sauverInstance(null, apporteur);
    List<String> extensions = new ArrayList<String>();
    extensions.add(ELEMENTSCONTENUS);
    extensions.add(TYPEELEMENT);
    extensions.add(VERSIONING);
    extensions.add(PARAMETRAGES);
    extensions.add(PARAMETRAGES + "." + PARAMETRES);
    return (ElementNiveauUn ) instanceService.lireInstanceParId(identifiant, extensions.toArray(new String[]{}));
}

这就是我想要做的事情

@Around(value = "execution(elementNiveauUn fr.generali.nova.atp.service.metier.impl.*.*(..)) && @annotation(traceable) && args(element)", argNames = "element,traceable")
public void serviceLayerTraceAdviceBasedElementInstanceAfter2(final ProceedingJoinPoint pjp,
                final ElementNiveauUn element, final Traceable traceable) throws SecurityException,
                NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    // current user
    String currentUserId = findCurrentUserId();

    // wether user is found or not
    boolean isUserFound = StringUtils.isBlank(currentUserId);

    // retrieve the oid of the returning type
    MethodSignature signature = (MethodSignature ) pjp.getSignature();
    Class<ElementNiveauUn> returnType = signature.getReturnType();

    Method[] methods = returnType.getMethods();
    Method method = returnType.getMethod("getOid", (Class< ? >[] ) null);
    String oid = (String ) method.invoke(null, (Object[] ) null);

    // log to database
    simpleTraceService.trace(element.getOid(), element.getVersioning().toString(), traceable.value(),
                    isUserFound ? UTILISATEUR_NON_TROUVE : currentUserId);
}

我的问题是这行代码

Class<ElementNiveauUn> returnType = signature.getReturnType();

允许我访问返回类型而不是实例

1 个答案:

答案 0 :(得分:8)

由于您有 around 建议,因此您需要调用pjp.proceed()以执行建议的方法,并返回其值:

@Around(...)
public Object serviceLayerTraceAdviceBasedElementInstanceAfter2(final ProceedingJoinPoint pjp,
                    final ElementNiveauUn element, final Traceable traceable) throws SecurityException,
                    NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    ...
    Object result = pjp.proceed();
    ...
    return result;
}