AspectJ - 使用类型间声明创建全局日志记录器字段 [英] AspectJ - Creating a global Logger field using an Inter-Type Declaration
问题描述
我想创建一个Inter-Type声明,在每个类中声明一个(静态final)Logger实例。
I'd like to create an Inter-Type declaration that declares a (static final) Logger instance inside each class.
构造函数应该传递封闭类 Klazz.class
value:
The constructor should be passed the enclosing class Klazz.class
value:
@Aspect
public class LoggerAspect {
public interface Logger {
}
public static class LoggerImpl implements Logger {
private static final Logger logger =
new Logger(thisJoinPoint.getTarget().getClass()/*.getName()*/);
}
@DeclareParents(value="com.my.api..*",defaultImpl=LoggerImpl.class)
private Logger implementedInterface;
}
我写了上面的解决方案,但是我不能使用 thisJoinPoint
以外的AspectJ 建议。
I wrote the above solution, however I'm unable to use thisJoinPoint
outside of an AspectJ advice
.
如果Logger默认实现应用于某些类Klazz,我如何修改上面的代码以成功传递Klazz.class到Logger构造函数?
If the Logger default implementation is applied to some class Klazz, how can I modify the above code to successfully pass Klazz.class to the Logger constructor?
推荐答案
您可以通过类型间声明在任何单个类上声明一个静态成员:
You can declare a static member on any single class via inter-type declaration:
public aspect LoggingAspect {
static Logger MyClass.someField = Logger.getLogger(MyClass.class.getName());
}
但这不是很灵活,因为你需要为每个单独的类。我只想提一下。
But this is not very flexible because you need to do it for each single class. I just wanted to mention it.
为了添加一些技术上不是但实际上是一个类的静态成员的东西,只需为你的日志方面使用每个类型的关联:
In order to add something which is not technically but effectively a static member to a class, just use per-type association for your logging aspect:
public aspect LoggingAspect
pertypewithin(org.foo..*) // per-type association
{
Logger logger;
after() : staticinitialization(*) { // run 1x after class-loading
logger = Logger.getLogger(
getWithinTypeName() // type associated with aspect instance
);
}
pointcut logged() : // what to log, e.g. public methods
execution(public * *(..)); // (pointcut could also be abstract
// and refined in sub-aspects)
before() : logged() {
logger.log(...); // logging action
}
}
它是一种常见模式 - 可以在Ramnivas Laddad的优秀书 AspectJ in action(第2版),第6.2章.4。在 AspectJ文档中也有提及。
An example similar to this one - it is a common pattern - can be found in Ramnivas Laddad's excellent book AspectJ in action (2nd edition), chapter 6.2.4. It is also mentioned in the AspectJ documentation.
这篇关于AspectJ - 使用类型间声明创建全局日志记录器字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!