在服务 class 方法上执行方面后,从服务接收到控制器 class 的响应为空

Response received from service to controller class is null after aspect gets executed on service class method

我有一个控制器 class,它进一步调用服务 class 方法。 AOP @Around 方面应用于服务 class 方法。

package com.hetal.example;

@RestController
public class CustomerController {
    @Autowired
    CustomerService customerService;

    @RequestMapping(value = "/getDetails", method = RequestMethod.GET)
    public String getCustomerDetails() {
        System.out.println("Inside controller class");
        String details = customerService.getDetails(custName);
        System.out.println("Customer details is = " + details); // prints null
    }
}
package com.hetal.example;

@Service
public class CustomerServiceImpl implements CustomerService {
    @Override
    public String getDetails(String custName) {
        //some code
        returns "Customer details";
    }
}

aspect被写成执行@AroundCustomerServiceImplgetDetails()

的方法getDetails()
package com.hetal.config;

public class JoinPointConfig {
   @Pointcut(value="execution(* com.hetal.example.CustomerService.getDetails(..) && args(custName)")) 
   public void handleCustomerDetails(String custName) {}
}
package com.hetal.config;

@Aspect
@Component
public class CustomerAspect {
   @Around("com.hetal.config.JoinPointConfig.handleCustomerDetails(custName)") 
   public Object aroundCustomerAdvice(ProceedingJoinPoint joinpoint, String custName) {
       System.out.println("Start aspect");
       Object result= null;
       try { 
          result = joinpoint.proceed();
          System.out.println("End aspect");
       }
       catch(Exception e) {}
    return result;
   }
}

执行如下,

  1. 控制器调用CustomerServiceImpl.getDetails方法。

  2. CustomerAspect 被调用,打印 "Start aspect"。 //建议前

  3. joinpoint.proceed() 调用实际的 CustomerServiceImpl.getDetails 方法。

  4. CustomerServiceImpl.getDetails returns 一个字符串 "Customer details" 并且控制返回到方面,打印 "End aspect" //after return advice

  5. 控制返回控制器 class 但收到的响应为空。

我想要在方面完成后从服务 class 返回到控制器 class 的响应。

提前致谢!!

是的,您的应用程序中存在一些编译问题,并且在 Aspect class 中出现了 belwo return 类型问题, 但主要问题是你的 Aspect class,它的 void return 类型因此作为 null 你应该 return 结果作为 object ,下面是代码

package com.hetal.config;
    @Aspect
    @Component
    public class CustomerAspect {

       @Around("com.hetal.config.JoinPointConfig.handleCustomerDetails(custName)") 
       public Object aroundCustomerAdvice(ProceedingJoinPoint joinpoint, String custName) {
           System.out.println("Start aspect");

           Object result= null;
           try { 
              result = joinpoint.proceed();
              System.out.println("End aspect");
           }
           catch(Exception e) {}
 return result;
       }
    }