温馨提示:本文翻译自stackoverflow.com,查看原文请点击:spring - Response received from service to controller class is null after aspect gets executed on service cla
spring spring-boot aop aspectj spring-aop

spring - 在服务分类上执行方面之后,从服务收到的对控制器类的响应为空

发布于 2020-03-30 21:31:32

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

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";
    }
}

一个方面被写入将被执行@Around的方法getDetails()CustomerServiceImpl

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被称为,打印“开始方面”。//在咨询之前

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

  4. CustomerServiceImpl.getDetails 返回字符串“客户详细信息”,然后控件返回到方面,在返回建议后打印“结束方面” //

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

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

先感谢您 !!

查看更多

提问者
Hetal Rachh
被浏览
169
Pandit Biradar 2020-01-31 18:38

是的,您的应用程序中的一些编译问题进行了这些更改,而Aspect类中出现了belwo返回类型问题,但是主要问题在于Aspect类,其返回类型为void,因此,如果为null,则应将结果作为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;
       }
    }