Search code examples
javaspringhibernateaop

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


I am using a search method which is inside my BaseRepository to return a list based on the search conditions given. I am using the hibernate query for that. Some of the values in that list would be encrypted. So i want to alter that list before it returning using spring AOP. The returnList in the following code contains the list of search result which i accessed using AOP. I am using a decrypt method to do decryption on the string in that list if the string is ecrypted. But how can i make changes in the following code to reflect in the exact result of search. I mean how the decryption done on the Aspect will reflect in original list.

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


            }

        }
    }

} 

Solution

  • Assuming that all strings need to be decrypted, you can just alter the arrays contained in the list:

    @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]);
                }
            }
        }
    }