2011-04-15 100 views
1

我使用spring AOP来建议我的服务方法,尤其是返回对象的方法,我希望在建议处理期间可以访问该对象。如何访问建议方法的返回对象实例

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

这里的谏方法的签名,方法返回一个基于方法参数中的数据的新实例,所以参数是不可用的

@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(); 

允许我有acces秒到不以实例

回答

6

返回类型,因为你有一个各地建议,你需要调用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; 
} 
+0

它的工作原理,非常感谢你 – 2011-04-15 15:56:07

+0

这是否也适用于原始类型? – Zeus 2016-05-25 21:39:26

+0

没关系,它的工作原理是自动包装类包装。 – Zeus 2016-05-25 21:55:29

相关问题