4
虽然试图获得请求对象的方面,我发现了两个解决方案。我想知道哪一个更好一些。这里是细节。在Aspect中访问HttpServletRequest对象。哪一个更好的解决方案提到两个解决方案
我想对'@myAnnotation'注解的所有方法执行myAspectMethod。所以,当Spring发现方法级别的@myAnnotation时,myAspectMethod将在我使用请求对象执行业务逻辑的地方执行。为了得到要求我发现了两个解决方案
进样请求对象的看点类像
下面@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 } }
通过发送请求的对象作为注解的方法参数和访问它直通参数列表收到
访问请求方面
@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 {
}
请求对象使用哪一个是从性能的角度看更好的上述两种不同方式之间?这是我想知道答案的重要问题。
每种方法的其他优点和缺点是什么。
谢谢@axtavt! 对于解决方案#1,我认为类似的东西,即如何将请求对象注入单例方面。当我实现并通过具有不同标题值的不同请求时,每当我获得期望值时。这意味着每个请求对象可以设置为单身bean。看起来春天按照范围优雅地处理它。这里是我遇到的优秀文章 [http://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes-other-injection] – Siddhant