如何解决关于具有字段的类的方法的 AspectJ 建议
我想写一个around建议,在调用proceed()之前将一个correlation-id设置到MDC中,并在它之后返回旧值。这是我走了多远:
public aspect CorrelationIdAspect
{
private pointcut notPrivateMethod() :
execution(!private * *(..));
private pointcut methodWithContract(Contract contract) :
execution( * *.*(Contract,..)) && args(contract,..);
Object around(Contract contract) : methodWithContract(contract) && notPrivateMethod()
{
String oldCorrelationId = MDC.get(Constants.CORRELATION_ID);
try
{
String id = contract.getId().toString();
MDC.put(Constants.CORRELATION_ID,id);
Object result = proceed(contract);
return result;
}
finally
{
MDC.put(Constants.CORRELATION_ID,oldCorrelationId);
}
}
}
现在我希望这个建议只应用于具有类型字段的类
org.apache.logging.log4j.Logger
因为 - 显然 - 没有记录器的类不需要设置和恢复相关性 ID。有人知道如何实现吗?
非常感谢!
解决方法
您想使用编译器选项 -XhasMember
(另请参阅 my other answer),可在此处的 Eclipse 中找到:
那你
- 为您的方面添加标记界面,
- 使用 ITD 来声明每个具有
static Logger
字段的类都应该实现该接口,并且 - 匹配标记接口及其所有实现类:
public aspect CorrelationIdAspect {
// 1. marker interface
private interface HasLogger {}
// 2. use ITD in order to declare that each class having a
// 'static Logger' field ought to implement that interface
declare parents :
hasfield(static Logger *) implements HasLogger;
private pointcut notPrivateMethod() :
execution(!private * *(..));
// 3. match on the marker interface and all its implementing classes
private pointcut hasLogger() :
within(HasLogger+);
private pointcut methodWithContract(Contract contract) :
execution(* *(Contract,..)) && args(contract,..);
Object around(Contract contract) :
methodWithContract(contract) && notPrivateMethod() && hasLogger()
{
System.out.println(thisJoinPoint);
return proceed(contract);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。