July 13, 2009

Spring AOP - Example

« Public-Key based asymmetic password hashing | Main | Spring AspectJ »

The aspect oriented programming makes it possible to introduce additional code to an existing business logic. Because of that it simplified the implementation of cross-cutting concerns. Spring AOP provides an easy way to realize the aspect oriented paradigma. What are cross-cutting concerns in detail or in which cases aspect oriented programming helps you to implement cross-cutting concerns?
Few examples:

  • Logging
  • Security
  • Transaction management
  • Locking
  • Event handling
  • Auditing
Spring uses proxies for loosely coupling, abstraction and for AOP. The following example works with Spring proxies and realizes a method interceptor. For transformation of your beans to proxies you can set aspectj-autoproxy - element in your application context file or you utilize the BeanNameAutoProxyCreator.

Example: MethodLoggingInterceptor

public class MethodLoggingInterceptor implements MethodInterceptor {

 public Object invoke(MethodInvocation method) throws Throwable {
  String classMethodIdentifier = method.getMethod().getDeclaringClass() + "." + method.getMethod().getName();
  System.out.println(classMethodIdentifier + " starts");
  Object result = method.proceed();
  System.out.println(classMethodIdentifier + " finished");
  return result;
<bean name="methodLoggingInterceptor" class="org.developers.blog.spring.aop.logging.MethodLoggingInterceptor"/>
<bean name="proxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
    <property name="beanNames">
    <property name="interceptorNames">
Rafael Sobek

Technorati Tags:

Posted by rafael.sobek at 6:45 PM in Spring


[Trackback URL for this entry]

Comment: vels at Do, 18 Nov 9:51 AM

good article.......

want to learn Logging using AOP (advice /pointcut)
u can find it here http://velmurugan-pousel.blogspot.com

Comment: Murali at Mi, 1 Dez 5:40 AM

Excellent tutorial for beginers!!! Thanks a lot!!!

Comment: Punam at Mi, 6 Apr 6:42 AM

the best Example for AOP...

Thank you very much !!!

Comment: Jeewz at Sa, 6 Aug 3:23 PM

Thank you. Nicely done.

Comment: naresh at Mo, 10 Okt 8:10 AM

Thank you,

Your comment:

(not displayed)

Live Comment Preview: