I have a logging aspect like this, it will print args, result or any other exceptions. I use aspectj-maven-plugin to compile this aspect. Then, the compiled result will be packaged to a jar. I will offer this jar to our maven repository, so they can depend this jar in their project. If they need log any request info, they just need write an annonation @Log at the method defination. I aslo want to offer "a package assign abilility": My colleage could set a package parameter when compile their project, then all the method invoke inside that package will be cut。
In summary, like the customPointCut in the following code, I want change the pointcut defination when I need this compiled asject in another project.
@Aspect
public class LogAspect {
static private final Logger log = Logger.getLogger(LogAspect.class);
@Pointcut("execution(@com.stellariver.milky.aspectj.tool.log.Log * *(..))")
private void annoPointCut() {}
@Pointcut("execution(* com.project.package..*.*(..))")
private void customPointCut() {}
@Around("annoPointCut() || customPointCut()")
public Object valid(ProceedingJoinPoint pjp) throws Throwable {
Object result = null;
try {
result = pjp.proceed();
} catch (Throwable throwable) {
throw throwable;
} finally {
log(xx,xx);
}
return result;
}
}
I could not find any parameterized aspect solution in aspect project or aspect-maven-plugin project
In Java, annotation values must be compile-time constants, so you cannot change them. This is not an AspectJ issue, but a Java limitation.
So what you do in AspectJ is to define your logging aspect as abstract and the package pointcut also as abstract:
Then, in your demo project, you override the abstract aspect, defining a concrete pointcut:
Now, you can remove the
@Logannotation from your sample class:When compiling with Maven, you willl see:
When running the sample program, the output will be:
See? There is no need to copy & paste the whole aspect. You simply make the package pointcut abstract and force consuming projects to override it. Clean and simple.
P.S.: If the consuming project would use load-time weaving instead of compile-time weaving, you could define the overriding aspect in aop.xml directly, no need to compile a source aspect or use AspectJ Maven Plugin at all in the consuming project. But CTW or LTW, both works nicely, the rest is up to you.