What is AspectJ good for? [closed]
Solution 1:
- permission check
- interrupt action that takes too long
- run action in separate thread or even in context of different process or event on other machine
- monitoring
- preparing any data / environment before call and processing results after call
- opening / closing resources
EDIT
Although many years passed since I gave this answer I decided to add the following to make the answer more complete.
- security check.
- fixes of incorrect or behavior of API that you cannot change. For example boolean method that returns
false
in some conditions but should returntrue
. You can fix this using AspectJ.
Solution 2:
The Wikipedia entry gives you a few more examples (but not that many). Typically, Aspect Oriented Programing should be use only to implement simple behaviours that are not part of core concern of a class and are common to different classes. As soon as you begin to put too much logic in your aspects, the code becomes really unreadable.
The aspect you suggest (logging, transaction, ...) are the most commonly used. I would add security as well.
Solution 3:
One can use AspectJ for enforcing some (design) rules.
- like every controller method need some special annotations
- every service/frontend/dto class must be located in a service/fronten/dto pacakge
- more mature thinks like: checking that setters do not have any logic.
Inject Mocks in classes that otherwise would create new instances by using new. Assume you have this code:
public void sendInvitationEmail(String address) {
InvitationEmail email = new InvitationEmail();
email.sendTo(address).send();
}
And need to replace email
by an mock. Then you could use an Aspect (@Pointcut("call(InvitationEmail.new(..))")
) to "inject" a mock. -- @See Blog JMock and AspectJ by Daniel Roop, as well as Spring Roo`s @MockStaticEntityMethods (Mock Static Methods using Spring Aspect)