Originally posted by Riyaz Abdul Kareem:
Can anyone explain what is AOP in spring and its diferences with DI?
Dependency Injection (DI) is basically a programming model where object are given other objects that they depend upon. This is in contrast to a more conventional model where objects create or lookup objects that they depend upon. The downside of creating or looking up your own dependencies is that you are coupled to those dependencies and can't exist without them. With DI, however, you are given your dependencies, typically by a container. When used along with interfaces, you only know about your dependencies through their interface...you know nothing of how they are created or how they're implemented. You could be dealing with a local POJO, a remote web service, an
EJB, or a mock implementation...you don't know and you don't care. As long as the object your given lives up to the requirements of its interface, you are happy.
AOP is a way of applying common functionality across multiple points in an application, without those points being aware that the functionality is being applied. A typical example of AOP is the use of declarative transactions. Without AOP, you might go to the effort of starting a transaction, performing your database work, then either committing or rolling back the transaction depending on whether or not the DB work was a success. No big deal, except that transaction management is probably not a core concern of your saveEmployeeInfo() method--the chief concern of that method is saving an employee's information. Using AOP, you can extract the transaction management functionality into an aspect, and then declaratively select places to apply it. Your saveEmployeeInfo() method now focuses solely on saving an employee's info and how no idea that it will be wrapped in an aspect that will start and then either commit or roll back a transaction.
So, in short, both DI and AOP are mechanisms for removing coupling from code. DI removes coupling between application objects, while AOP decouples application concerns.