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

问题描述 投票:0回答:1

我有一个控制器类,它进一步调用服务类方法。 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. 控制返回到控制器类,但收到的响应为空。

完成方面后,我希望响应从服务类返回到控制器类。

提前谢谢您!

spring spring-boot aop aspectj spring-aop
1个回答
0
投票

[是的,您的应用程序中的一些编译问题会进行这些更改,而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;
       }
    }
© www.soinside.com 2019 - 2024. All rights reserved.