Spring AOP可以实现通用返回类型

时间:2017-06-27 07:40:37

标签: java spring-aop

我尝试使用类似

的通用注释创建Aspect
@Aspect
@Component
public class CommonAspect<T extends CommonEntity>{


    @AfterReturning(value = "@annotation(audit)",returning="retVal")
    public void save(JoinPoint jp,T retVal, Audit audit) {

        Audit audit = new Audit();
        audit.setMessage(retVal.getAuditMessage());
        //other code to store audit

    }


}

这可能吗?它在我的情况下失败了。 我想对人,用户等不同类型的实体使用这个@Audit注释。所以返回值可以是通用的。

1 个答案:

答案 0 :(得分:1)

您似乎正在尝试为返回CommonEntity的方法定义方面。 在这种情况下,您不需要使用泛型,您可以删除泛型声明并稍微调整您的方面声明:

@Aspect
@Component
public class CommonAspect {


    @AfterReturning(value = "@annotation(audit) && execution(CommonEntity *(..))",returning="retVal")
    public void save(JoinPoint jp, CommonEntity retVal, Audit audit) {

        Audit auditInfo = new Audit();
        auditInfo.setMessage(retVal.getAuditMessage());
        //other code to store audit

    }


}

我所做的是替换参数列表中的T并将execution(CommonEntity *(..))添加到切入点表达式,以限制匹配到返回CommonEntity的切入点。

相关问题