I have a controller class which further calls service class method. An AOP @Around
aspect is applied on the service class method.
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";
}
}
An aspect is written to be executed @Around
the method getDetails()
of 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;
}
}
Execution goes as below,
Controller calls CustomerServiceImpl.getDetails
method.
CustomerAspect
is called, prints "Start aspect". //before advice
joinpoint.proceed()
calls actual CustomerServiceImpl.getDetails
method.
CustomerServiceImpl.getDetails
returns a string "Customer details" and control comes back to the aspect, prints "End aspect" //after returning advice
Control goes back to controller class but the response received is null.
I want the response returned from the service class into the controller class after the completion of the aspect.
Thank you in advance !!
Yeah you some compilation issue in your applications make those changes and with the belwo return type issue in Aspect class, but the main issue is with your Aspect class, its void return type hence that coming as null you should return the result as object , below is the code
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;
}
}