我是aspectj的新手...
我编写了以下方面,旨在将日志记录添加到类型的函数调用中public * doSomething*(..)
。如果我的主类是同一个项目的一部分,则方面的编织不会出现故障并且代码会执行。如果我将编织的代码打包到一个 jar 中并从另一个 Eclipse 项目中调用它 - 建议不会执行。另一种情况是仅将方面(.aj)打包到一个单独的 jar 中,并将该 jar 添加到 eclipse 中的“方面路径”中,这使 eclipse 能够正确地编织方面。事情是我需要把它包装成一个罐子,然后从其他地方调用代码。那也不起作用(我想这并不奇怪......)为什么?
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.CodeSignature;
import org.apache.log4j.Logger;
public aspect Logging {
pointcut allPublic(): !cflow(call(public void main(..))) && (call(public * doSomething*(..)));
private static final Logger log = Logger.getLogger("Logging.aspect");
@SuppressWarnings({"unchecked", "unused"})
private void printParameters(JoinPoint jp) {
CodeSignature methodSignature = (CodeSignature) jp.getSignature();
String methodName = methodSignature.getName();
Object[] paramNames = methodSignature.getParameterNames();
Class[] paramTypes = (Class[])methodSignature.getParameterTypes();
Object[] paramObjects = jp.getArgs();
StringBuffer infoMsg = new StringBuffer();
infoMsg.append("Entering function: " + methodName);
if (paramNames != null && paramNames.length > 0){
if (paramNames.length == 1){
infoMsg.append(" with input parameter: ["+ paramNames[1]+ "] = [" + paramObjects[1] + "]");
}
else {
infoMsg.append(" with input parameters: ");
}
for (int i = 1; i < paramNames.length; i++) {
infoMsg.append(" [" + paramTypes[i].getName() + " " + paramNames[i]+ "] = [" + paramObjects[i] + "]");
}
}
else {
infoMsg.append(" NONE");
}
log.info(infoMsg.toString());
}
@SuppressWarnings("unused")
private void printExit(JoinPoint jp) {
log.info("Exit function: " + jp.getSignature().toString());
}
before() : allPublic() {
printParameters (thisJoinPoint);
}
after() : allPublic() {
printExit(thisJoinPoint);
}
}
应该被告知的课程:
public class Main {
private static final Logger log = Logger.getLogger("A.class");
public static void doSomethingAa(int number, String message, Map<String, String> map){
log.debug("A");
}
public static void doSomethingB(int id, String name){
log.debug("B");
}
public static void main(String[] args){
Map<String, String> map1 = new TreeMap<String, String>();
Map<String, String> map2 = new TreeMap<String, String>();
map1.put("FirstKey", "FirstValue");
map1.put("SecondKey", "SecondValue");
map2.put("Tal", "Guy");
map2.put("Happy", "Birthday");
A.doSomethingAa(17, "Tal", map1);
A.doSomethingAa(35, "Guy", map2);
A.doSomethingB(12, "TalG");
A.doSomethingB(40, "GuyG");
System.out.println("Finished running main");
}
}
谢谢大家!