Why proxy class is required for Spring AOP?
What is th开发者_Python百科e responsibity of the proxy class in AOP? What is the role of that?
Dynamic proxies are used to execute additional code before/after methods of your beans. The most trivial example is transaction handling:
- spring creates a proxy around your beans that need transactions
- if a method is declared transactiona (e.g. annotated with
@Transactional
) the proxy starts a new transaction and delegates to the real method - the real method executes and returns
- the proxy now commits (or rollbacks) the transaction
Thus your code becomes transaction-agnostic. And when a transactional bean is injected into another one, it is actually the proxy that gets injected (which is of the same type as your bean)
And proxies are dynamic, because spring does not know at compile time the types of all your beans, so it has to create the proxies at runtime.
精彩评论