Home > Software engineering >  @Afterreturning advice from Spring AOP doesn't work when I bind returning result to it
@Afterreturning advice from Spring AOP doesn't work when I bind returning result to it

Time:03-20

Here's advice

@AfterReturning(
        pointcut = "execution(public java.util.List<me.mikholskiy.domains.Customer> me.mikholskiy.daos.CustomerDao.getAll())",
        returning = "resultList")
public void adviceBeforeGetAllCustomersFromDatabase(JoinPoint joinPoint,
                                                    List<Customer> resultList) {
    // ... 
}

So when I use this advice annotation without returning parameter, it works as expected. But when I want to bind returning result to this advice nothing happens. It doesn't even executed.

Here's target method for this advice:

@Override
public List<Customer> getAll() {
    return sessionFactory.getCurrentSession()
        .createQuery("from Customer", Customer.class)
        .list();
}

I use this dependencies

org.springframework:spring-webmvc:5.3.17
org.springframework:spring-aspects:5.3.17
org.aspectj:aspectjweaver:1.9.7

CodePudding user response:

Unable to match type List<Customer> because returning clause also restricts matching to only those method executions that return a value of the specified type (Object or it’s subtypes in this case, which will match any return value).

So, in your code, instead of:

public void adviceBeforeGetAllCustomersFromDatabase(
    JoinPoint joinPoint, List<Customer> resultList) {
...

Try with:

public void adviceBeforeGetAllCustomersFromDatabase(
    JoinPoint joinPoint, Object resultList) {
...
  • Related