What is AspectJ good for? [closed]

回眸只為那壹抹淺笑 提交于 2019-11-28 03:12:08
  • 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 return true. 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.

Ralph

One can use AspectJ for enforcing some (design) rules.


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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!