我有一个控制器类,它进一步调用服务类方法。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;
}
}
我尝试通过更改返回类型来返回收到的结果,但是它不起作用。
我已经测试了对我有用的相同代码,您也可以测试,下面是git hub链接github.com/panditb/stackdemos
它成功了,谢谢您的解决方案@Pandit Biradar