如何使用 spring AOP 更改列表中的 return 值?

How to alter the return values in a list using spring AOP?

我正在使用 search 方法,它位于我的 BaseRepository 到 return 基于给定搜索条件的列表中。我正在为此使用休眠查询。该列表中的某些值将被加密。所以我想在 returning 使用 spring AOP 之前更改该列表。以下代码中的 returnList 包含我使用 AOP 访问的搜索结果的 list。如果字符串被加密,我正在使用解密方法对该列表中的字符串进行解密。但是我如何更改以下代码以反映搜索的确切结果。我的意思是在 Aspect 上完成的解密将如何反映在原始列表中。

@Aspect
@Service
public class DecryptionAspect {

    @AfterReturning(value="(execution(* search(..)) )" +
            "&& target(com.erp.core.repo.IBaseRepository) " +
            "&& args(..)",returning="returnList")
    public void decrypt(List returnList) throws Exception
    {

        Iterator itr = returnList.iterator();
        while(itr.hasNext()){
            Object[] obj = (Object[]) itr.next();
            for(int i=0;i<obj.length;i++){
                if(obj[i]!=null)
                EncryptUtil.decrypt(obj[i].toString());


            }

        }
    }

} 

您可以尝试替换列表中的元素"returnList"。

@AfterReturning(value="(execution(* search(..)) )" +
        "&& target(com.erp.core.repo.IBaseRepository) " +
        "&& args(..)",returning="returnList")
public void decrypt(List returnList) throws Exception
{

    Iterator itr = returnList.iterator();
    int count=0;
    while(itr.hasNext()){
        Object[] obj = (Object[]) itr.next();
        Object[] newObjects = new Object[obj.length];
        for(int i=0;i<obj.length;i++){
            if(obj[i]!=null)
            String decryptedText = EncryptUtil.decrypt(obj[i].toString());
            newObjects[i] = decryptedText;
        }
        returnList.set(count,newObjects);
        count++;
    }
}

假设所有的字符串都需要解密,你可以只改变列表中包含的数组:

@AfterReturning(value="(execution(* search(..)) )" +
        "&& target(com.erp.core.repo.IBaseRepository) " +
        "&& args(..)",returning="returnList")
public void decrypt(List returnList) throws Exception
{
    for (Object [] objs : (List<Object[]>) returnList) {
        for (int i = 0; i < objs.length; i++) {
            if (objs[i] instanceof String) {
                objs[i]= EncryptUtil.decrypt(objs[i]);
            }
        }
    }
}