java - Access HttpServletRequest object inside Aspect. Which one is better solution between two solutions mentioned -
while trying request object in aspect found 2 solutions. know performance wise 1 better. here details.
i wanted execute myaspectmethod methods annotated '@myannotation'. ever spring finds @myannotation @ method level myaspectmethod executed using request object perform business logic. request found 2 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 request object } }
by sending request object argument in annotated method , access thru 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 request object } private httpservletrequest getrequestargument(proceedingjoinpoint pjp) { (object object : pjp.getargs()) { if (object instanceof httpservletrequest) { return (httpservletrequest) object; } } return null; } } @retention(retentionpolicy.runtime) @target(elementtype.method) public @interface myannotation { }
between above 2 different ways of request object usage 1 better performance perspective? important question know answer.
what other pros , cons of each approach.
i'm not sure first method works. if can autowire
httpservletrequest
way, you'll have make aspect request-scoped.i think best option use
requestcontextholder
:httpservletrequest request = ((servletrequestattributes) requestcontextholder.currentrequestattributes()).getrequest();
this method uses thread-local storage populated spring , doesn't need changes in method signature.
Comments
Post a Comment