What is AspectJ good for? [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
开发者_StackOverflowClosed 8 years ago.
Improve this questionFirst let me note, that I use AspectJ and I like it, but what else can I do with it.
I know AspectJ can be/is used for Logging. In some cases it is used for Transaction controlling – mostly implemented in conjunction with annotations. AspectJ can also be used to enhance classes with (code-generated) methods, like Spring Roo does.
But I believe AspectJ and AOP in general, can be used for more than: logging, transaction controlling, and simulation partial classes.
So what are other useful use cases for AspectJ and AOP?
- 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.
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.
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)
精彩评论