我有一个控制器类,它进一步调用服务类方法。 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;
}
}
执行如下,
控制器调用CustomerServiceImpl.getDetails
方法。
CustomerAspect
被调用,打印“开始方面”。 //之前的建议
[joinpoint.proceed()
调用实际的CustomerServiceImpl.getDetails
方法。
[CustomerServiceImpl.getDetails
返回字符串“客户详细信息”,并且控件返回到方面,打印“结束方面” //在返回建议之后
控制返回到控制器类,但收到的响应为空。
完成方面后,我希望响应从服务类返回到控制器类。
提前谢谢您!
[是的,您的应用程序中的一些编译问题会进行这些更改,而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;
}
}