Imagine you have an aspect:
@Aspect
public class MyAspect {
@Pointcut("whatever")
public void anyAnnotation() {}
@Before("anyAnnotation()")
public void anyComponentAdvice(JoinPoint joinPoint) {
System.out.println("DONE");
}
}
And you have a simple app:
public class MyClass {
public static void main(String[] args) {
// ASPECTJ INITIALIZATION BLOCK
// rest of the code
}
}
What code do you need to put into the “aspectj initialization block” for the application to automatically recognize and apply the aspects?
With some frameworks such as Spring AOP you can use <aop:aspectj-autoproxy/>, but I do not know how to do the same without Spring.
Edit: other simpler ways to intercept method calls at execution time, without aspects, are welcome.
From what I recall of AspectJ, it works by “weaving” the aspects into the existing code by modifying the bytecode as a build step or when the classes are loaded. Neither of these can be done from your main() method in a straightforward fashion.
The not-straightforward fashion involves loading your application code using a custom classloader mentioned in the docs.
For a standalone application, AspectJ is probably still the best way to do what you’re trying to – but using build-time weaving. Your IDE, Ant, and Maven should all support this. The official documentation includes how to use the Ant tasks. The documentation for the Maven plugin is here. You can also use the
ajccommand if you build with a shell script. As for the IDE plugins, I’m merely aware they’re around, not familiar with their use.