我碰巧有一个@Aspect,它声明了一个被另一个方面的切入点截获的方法。方面是使用编译时编织创建的,容器是使用Spring实例化的。
我用@Configurable注释了我的方面,告诉Spring组件是在容器外部创建的。在这个方面,我碰巧也有一个对Log对象的静态引用。总而言之,代码如下所示
@Aspect
@Configurable
public class MyAspect {
private static final Log log = LogFactory.getClass(MyAspect.class);
// Autowired dependencies
// Pointcuts and advice
// Happens to be a pointcut of some other Advice
@Asynchronous
private Object someMethod(...) {
}
}在AspectJ编译过程中,我没有看到我期望的消息,如下所示:
weaveinfo Join point 'method-call(java.lang.Object mypackage.someMethod(...))' in Type 'mypackage.MyAspect' (MyAspect.java:30) advised by around advice from 'anotherpackage.AsynchronousAspect' (from AsynchronousAspect.java))正如预期的那样,在这一点上永远不会调用第三方建议。但是,如果我将一个简单的日志条目添加到我的建议中,如下所示
log.debug("Join point invoked!");然后正确地进行编译,并且所有方面都被连接(包括我的第三方依赖项)并被正确地调用。
添加日志条目对更改我的假设有什么作用?
发布于 2013-03-15 21:03:11
如果你知道自己在做什么,你想要做的事情是非常简单的,而且一点也不危险。请道歉,我不是Spring用户,比起@AspectJ,我更喜欢原生AspectJ语法。这个小示例运行得很好:
public class Application {
public static void main(String[] args) {
System.out.println("Hello world!");
someMethod();
}
private static void someMethod() {
System.out.println("Doing something ...");
}
}public aspect FirstAspect {
void around() : execution(void *..main(..)) {
System.out.println(thisJoinPointStaticPart + ": " + someMethod("before", "main"));
proceed();
System.out.println(thisJoinPointStaticPart + ": " + someMethod("after", "main"));
}
private Object someMethod(String position, String methodName) {
return position + " " + methodName;
}
}public aspect SecondAspect {
Object around() : execution(* *..someMethod(..)) {
System.out.println(thisJoinPointStaticPart + ": before someMethod");
Object result = proceed();
System.out.println(thisJoinPointStaticPart + ": after someMethod");
return result;
}
}结果不出所料:
execution(Object FirstAspect.someMethod(String, String)): before someMethod
execution(Object FirstAspect.someMethod(String, String)): after someMethod
execution(void Application.main(String[])): before main
Hello world!
execution(void Application.someMethod()): before someMethod
Doing something ...
execution(void Application.someMethod()): after someMethod
execution(Object FirstAspect.someMethod(String, String)): before someMethod
execution(Object FirstAspect.someMethod(String, String)): after someMethod
execution(void Application.main(String[])): after main此外,如果您关心方面的应用/执行顺序,请使用declare precedence。
如果你在访问私有成员时遇到问题,你需要使用privileged aspect。
更新:将thisEnclosingJoinPointStaticPart的用法更改为thisJoinPointStaticPart。这只是一个复制和粘贴错误。在execution连接点上的结果是相同的,但无论如何,更正更好地显示了代码的意图。
https://stackoverflow.com/questions/15350179
复制相似问题