While trying to get request object in Aspect I found two solutions. I would like to know performance wise which one is better. Here are the details.
I wanted to execute myAspectMethod for all methods annotated by '@myAnnotation'. So where ever spring finds @myAnnotation at method level myAspectMethod will be executed where I am using request object to perform business logic. To get request I found two solutions
Inject request object in Aspect class like
below
@Aspect
public class MyAspect {
@Autowired(required = true)
**private HttpServletRequest request;**
@Around("@annotation(myAnnotation)")
public Object myAspectMethod(ProceedingJoinPoint pjp,
MyAnnotation myAnnotation) throws Throwable {
//....do something with request object
}
}
By sending request object as argument in annotated method and access it thru the argument list received
Access request in Aspect
@RequestMapping(method = { RequestMethod.GET }, value = "/something")
@MyAnnotation
public Object myAnnotatedMethod(**HttpServletRequest request**)
{
//....some business logic
}
@Aspect
public class MyAspect {
@Around("@annotation(myAnnotation)")
public Object myAspectMethod(ProceedingJoinPoint pjp,
MyAnnotation myAnnotation) throws Throwable {
HttpServletRequest request = getRequestArgument(pjp);
....do something with request object
}
private HttpServletRequest getRequestArgument(ProceedingJoinPoint pjp) {
for (Object object : pjp.getArgs()) {
if (object instanceof HttpServletRequest) {
return (HttpServletRequest) object;
}
}
return null;
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
}
Between above two different ways of request object usage which one is better from performance perspective? This is important question for which I would like to know the answer.
What are the other pros and cons of each approach.
I'm not sure that the first method works. Even if you can autowire HttpServletRequest
this way, you'll have to make your aspect request-scoped.
I think the best option would be to use RequestContextHolder
:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
This method uses a thread-local storage already populated by Spring and doesn't need any changes in your method signature.