Aquí es mi sencilla aplicación para registrar entrar, salir y excepciones a los métodos
anotación
package test;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface Audit {
}
ingrese Interceptor
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.logging.Level;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
@Aspect
public class ExceptionInterceptor {
private static final java.util.logging.Logger LOGGER = java.util.logging.Logger.getLogger(ExceptionInterceptor.class.getName());
@Around("execution(* * (..))"
+ " && @annotation(test.Audit)"
)
public Object intercept(final ProceedingJoinPoint point) throws Throwable {
final Method method
= MethodSignature.class.cast(point.getSignature()).getMethod();
String mName = method.getName();
String cName = method.getDeclaringClass().getSimpleName();
LOGGER.log(Level.INFO, "Entering {0}:{1}", new Object[]{cName, mName});
Object out = null;
try {
out = point.proceed();
} catch (Throwable t) {
logExceptions(t, point);
}
LOGGER.log(Level.INFO, "Exiting {0}:{1}", new Object[]{cName, mName});
return out;
}
private void logExceptions(Throwable t, final ProceedingJoinPoint point) {
final Method method
= MethodSignature.class.cast(point.getSignature()).getMethod();
String mName = method.getName();
String cName = method.getDeclaringClass().getSimpleName();
Object[] params = point.getArgs();
StringBuilder sb = new StringBuilder();
sb.append("Exception caught for [");
sb.append(cName);
sb.append(".");
sb.append(mName);
for (int i = 0; i < params.length; i++) {
Object param = params[i];
sb.append("\n");
sb.append(" [Arg=").append(i);
if (param != null) {
String type = param.getClass().getSimpleName();
sb.append(", ").append(type);
// Handle Object Array (Policy Override)
if (param instanceof Object[]) {
sb.append("=").append(Arrays.toString((Object[]) param));
} else {
sb.append("=").append(param.toString());
}
} else {
sb.append(", null");
}
sb.append("]");
sb.append("\n");
}
LOGGER.log(Level.SEVERE, sb.toString(), t);
}
}
Como Usar
@Audit
public void testMethod(Int a,int b, String c){
}
dependencias Maven Compilar
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.7</version>
</dependency>
Tejiendo
<plugin>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-maven-plugin</artifactId>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>ajc</goal>
</goals>
</execution>
</executions>
</plugin>
Sí, tiene sentido. AspectJ es de código abierto, al igual que Javaassist. – Perception