2011-04-15 31 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

相關問題