我正在处理一个注释,该注释将向其他微服务发送一些审核事件。比方说,我正在创建一个实体,并且我的Rest控制器上有一个方法add。
@PostMapping
@Audit
public ResponseEntity<EntityDTO> add(EntityDTO entity){
...
}我定义了一个与@Audit注释相关联的适当方面。
但是这里有一个技巧,审计事件的性质决定了我需要从HttpServletRequest本身提取一些元数据。
而且我不想通过添加(或替换我唯一的参数) HttpServletRequest对象来修改我的签名。
我如何将HttpServletRequest传递到我的方面中?有什么高雅的方法吗?
发布于 2020-05-28 05:06:30
由于您使用的是spring MVC,请考虑使用Spring MVC拦截器而不是“通用”方面。它们由Spring MVC原生支持,并且可以提供对处理程序和HttpServletRequest对象的访问
有关使用拦截器和常规配置的信息,请参见this tutorial
有关处理程序的一些信息,请参见This thread
final HandlerMethod handlerMethod = (HandlerMethod) handler; // this is what you'll get in the methods of the interceptor in the form of Object
final Method method = handlerMethod.getMethod();发布于 2020-05-28 10:17:40
下面是如何使用Spring AOP来完成此操作。
示例注释。
@Retention(RUNTIME)
@Target({ TYPE, METHOD })
public @interface Audit {
String detail();
}以及相应的方面
@Component
@Aspect
public class AuditAspect {
@Around("@annotation(audit) && within(com.package.web.controller..*)")
public Object audit(ProceedingJoinPoint pjp, Audit audit) throws Throwable {
// Get the annotation detail
String detail = audit.detail();
Object obj = null;
//Get the HttpServletRequest currently bound to the thread.
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
try {
// audit code
System.out.println(detail);
System.out.println(request.getContextPath());
obj = pjp.proceed();
} catch (Exception e) {
// Log Exception;
}
// audit code
return obj;
}
}注: Op已接受基于拦截器的答案。这个答案就是演示Spring AOP代码来实现这个要求。
希望这能有所帮助
https://stackoverflow.com/questions/62052618
复制相似问题