如何使用AspectJ过滤方法的返回值?

时间:2011-08-30 09:01:03

标签: java methods annotations aspectj signature

我想过滤具有@Filter注释的方法的返回值,并按某个谓词返回CollectionArrayMap

我尝试过类似的事情:

    @Pointcut("execution(@example.annotations.Filter * *(..)) "
            + "&& @annotation(filter) ")
    public void filterOperation(final Filter filter) {
        /* ... */
    }

但如果我将execution((java.util.Collection+ || java.util.Map+) * * (..))添加到上面的PointCut,我会收到语法错误。

如果某个方法使用@Filter进行注释但是不会返回集合,那么解决方案的外观如何,最好是我可能会出错?

1 个答案:

答案 0 :(得分:3)

您是否尝试过使用execution((java.util.Collection+ || java.util.Map+) *.* (..))

或者您可以使用:

@Pointcut("execution(@example.annotations.Filter java.util.Collection+ || java.util.Map+ *(..)) "
        + "&& @annotation(filter) ")
public void filterOperation(final Filter filter) {
    /* ... */
}

您可以通过以下方式处理返回值:

@AfterReturning(value="filterOperation(filter)", returning="collection")
public void handlingReturnValue(final Filter filter, Object collection) {
    System.out.println(collection);
}

但我想最好为MapCollection s使用单独的建议:

@Pointcut("execution(@Filter java.util.Collection+ *(..)) "
        + "&& @annotation(filter) ")
public void filterCollection(final Filter filter) {
    /* ... */
}

@Pointcut("execution(@Filter java.util.Map+ *(..)) "
        + "&& @annotation(filter) ")
public void filterMap(final Filter filter) {
    /* ... */
}

@AfterReturning(value="filterCollection(filter)", returning="collection")
public void handlingReturnCollection(final Filter filter, Collection collection) {
    System.out.println(collection);
}

@AfterReturning(value="filterMap(filter)", returning="map")
public void handlingReturnMap(final Filter filter, Map map) {
    System.out.println(map);
}