05 July 2011
If you've ever read about Spring's powerful AOP support then you've probably heard about the canonical example of introducing logging functionality - a cross-cutting concern - to your beans. The example goes like this: you want to log the start and stop time for every method invocation. You can either modify every method and introduce logging, which is tedious and error-prone, or you can simply use AOP to wrap every method invocation. With AOP, you'll get a chance to perform logging every time a method is started and finished, or both! This is a common example, but it doesn't even begin to illustrate how powerful AOP can be. The most powerful example of AOP is perhaps the Spring framework itself. It uses it every where! Let's look at some common examples:
JdbcTemplate) so consumers never need to know. This usually ends up being the most performant, and most natural, style of Spring bean. One example where Spring uses AOP to acheive the feeling of thread-safety without concerning the developer with it is in Spring's
EntityManagersupport. Spring will correctly inject a proxy
EntityManagers are not thread-safe, but the consumer doesn't need to know. As an example, you might write:
@PersistenceContext EntityManager em.Spring then automatically routes all concurrent requests to the appropriate, thread-local instance being maintained in the background.