Spring by examples – method interceptors

Spring is a great Java technology that has become a very popular application framework during the past few years. My intention is not to go through the whole concepts and architectural details of the framework, because that kind of information can be easily looked up starting at http://www.springframework.org. As the article title indicates, I intend to provide hands-on examples showing the minimal requirements to bundle certain Spring functionalities in your Java applications. So, because I will not go into the “what’s under the hood” approach unless absolutely necessary, most of the examples might require the knowledge of basic Spring concepts. Anyway, the basic idea is that you must RTFM before deciding if Spring is right for your application.

The first example is a short look at a simple method intercepting strategy. You can read all about this and the whole Spring AOP API here.The source code for this example can be found here. In the project directory run ant compile run to launch the application.

For the beginning let’s consider that we have the service MyService that that has a method doSomething() performing an operation which takes a long time to execute. Below you can see the (pretty dumb) code of this method.

public class MyService {
  public void doSomething() {
    for (int i = 1; i < 10000; i++) {
      System.out.println("i=" + i);
    }
  }
}

In order to print out the performance statistics on the method call, we must first implement the interceptor that actually calculates the execution time for this method. To do this we need to implement the org.aopalliance.intercept.MethodInterceptor interface shipped with Spring. This is actually a callback providing access to the actual call of the methods of our service. The JavaDoc for this interface is here.

public class ServiceMethodInterceptor implements MethodInterceptor {
  public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    long startTime = System.currentTimeMillis();
    Object result = methodInvocation.proceed();
    long duration = System.currentTimeMillis() - startTime;
    Method method = methodInvocation.getMethod();
    String methodName = method.getDeclaringClass().getName() + "." + method.getName();
    System.out.println("Method '" + methodName + "' took " + duration + " milliseconds to run");
    return null;
  }
}

Next we need to proxy our service in order to obtain an instance whose methods are being intercepted by our ServiceMethodInterceptor. To achieve this, all it takes is a little magic in Spring’s bean configuration file, as you can see below.

<beans>
  <bean id="myService" class="com.test.MyService">
  </bean>

  <bean id="interceptor" class="com.test.ServiceMethodInterceptor">
  </bean>

  <bean id="interceptedService" class="org.springframework.aop.framework.ProxyFactoryBean">
    <property name="target">
      <ref bean="myService"/>
    </property>
    <property name="interceptorNames">
      <list>
        <value>interceptor</value>
      </list>
    </property>
  </bean>
</beans>

The key in this XML snippet is Spring’s built-in class org.springframework.aop.framework.ProxyFactoryBean which provides the actual proxying of our service. In order to obtain the desired effect we must set the target and interceptorNames properties for this bean. The target property represents the name of the bean that we want to proxy, which in our case is the myService bean. The interceptorNames property holds a list of bean names that will be used as interceptors for the proxied bean. So, yes, you can define more than one interceptor for your bean.
As everything seems to be packed pretty nice, all we need to do now is to have our service instantiated using Spring and call itâs doSomething method.

public class Test {
  public static void main(String[] args) {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("com/test/applicationContext.xml");
    MyService myService = (MyService)ctx.getBean("interceptedService");
    myService.doSomething();
  }
}

So we need to look up the interceptedService bean in order to get the proxied service, but if we choose to remove the performance monitor we can simply lookup the initial myService bean.
Normally, after the method doSomething has run, you should see, as the last output line, something like this:

Method 'com.test.MyService.doSomething' took 281 milliseconds to run

Except from the MethodInterceptor Spring also offers other method interception strategies. For example you can choose to handle a method execution right before or immediately after the actual call, or when an exception is thrown during the execution of your method. The reference documentation about these types of interceptors that Spring offers is available here.

Please note that basic performance monitoring can also be achieved by using Spring’s built-in PerformanceMonitorInterceptor. We used this logic just as a sample for method intercepting, but as your intuition might tell you, this is just one of the many things you can do with this feature of Spring. For example, if you need to implement a fine-grained security module, you might choose not to allow the method call to execute if the user does not have rights on the business method. So, basically, you will have to see for yourself how you can use this functionality in your application.

I hope you find this article useful.
Have a happy coding day :) .

34 comments ↓

#1 mircea ciorba on 10.25.06 at 12:04 am

great article. easy to digest and straight to the point. i hope this will end up in a series that you will then arrange in a nice tutorial. :)
keep it up, dude.

#2 Mircea Ciorba on 07.05.07 at 12:48 am

Dude, what happened to the Spring series? I really liked the first two articles. Keep on writing…

#3 ikaschenko on 07.21.08 at 3:59 am

One more alternative to proxy beans without redefinition. Interceptor is introduced as completely external artifact.


interceptor

#4 Shashika SK on 07.01.09 at 2:53 am

Thanx Buddy for your Article. Great one.

#5 Nisarg Panchal on 04.10.10 at 12:21 pm

Nice example…easy to understand & straight forward!

Thanks.

#6 Sameer Sood on 07.20.10 at 2:13 am

Good article
appreciated!!

#7 Guru on 01.10.11 at 11:07 pm

Superb article!!

#8 porn hub on 01.17.11 at 1:08 pm

ceuc eaauc xnxx elipwy g kq s lvj

#9 Hilary Kuree on 01.24.11 at 4:19 pm

Rather nice blog you’ve got here. Thanx for it. I like such topics and anything connected to this matter. I definitely want to read more on that blog soon.

Hilary Kuree
independent escorts in new york

#10 PXStevey on 01.25.11 at 4:01 am

Hi, I’m new I would like to welcome all… :)

#11 speedd on 02.04.11 at 12:10 pm

Hi, regards all :)
Filmy

#12 inolaaccilm on 02.08.11 at 1:27 am

one system pencils cased cased 2 aaa andy motorcycle black essentials history word 1999 fruits http://www.tubenice.tk
http://www.wikishopping.tk

#13 payday loans in houston texas on 02.22.11 at 1:12 am

369 BC

#14 ReortMart on 03.02.11 at 11:46 pm

treba zkontrolovat:)

#15 trieriCliesse on 03.11.11 at 5:39 pm

Enthusiastic collection, I believe you have to modify the proof of gamblers. Here you can put a fatal check, I judge that you need for your gift tags. Appropriate the wealth.

#16 Anete Swenson on 03.11.11 at 8:14 pm

Pretty interesting blog you’ve got here. Thanks the author for it. I like such themes and everything connected to this matter. I would like to read more on that blog soon.

Anete Swenson
call girl escort milano

#17 AnnabelleBurke33 on 04.14.11 at 7:44 am

I took my first personal loans when I was a teenager and this helped my relatives very much. But, I require the small business loan again.

#18 meilleur casino on 04.21.11 at 7:04 am

casino en ligne…

[...] Here’s a brief summary of what’s going on with. [...]…

#19 foster on 04.26.11 at 12:35 am

great and thorough explanation with skillful demonstration

#20 Hello on 05.03.11 at 12:50 am

Injected

#21 Alice on 05.03.11 at 12:52 am

Hello

#22 Alice on 05.03.11 at 12:53 am

for(i=0; i < 10; i++)
alert("Good One..");

#23 Alice on 05.03.11 at 12:54 am

click here

#24 Alice on 05.03.11 at 12:56 am

Click it

#25 Alice on 05.03.11 at 12:57 am

Click isn’t working! Good Job!

#26 Julia Simpson on 05.19.11 at 7:27 pm

It was very interesting for me to read this article. Thanks the author for it. I like such topics and anything that is connected to them. I definitely want to read a bit more soon.

Julia Simpson
mobile phone jamming

#27 Fashion clothing store on 05.20.11 at 2:02 am

Thanks for the information! One more alternative to proxy beans without redefinition. Interceptor is introduced as completely external artifact.

#28 lizeenlarge on 06.03.11 at 10:43 pm

casino , jogos de cassino , slots. internet casino.

#29 HP Pavilion on 06.14.11 at 9:54 pm

Awesome! This blog looks word for word like my prehistoric identical! It’s on a absolutely other issue but it has pretty much the regardless layout and design. Vast select of colors!

#30 SInettintY on 06.24.11 at 2:20 pm

how to unlock iphone 4
unlock iphone 4

how to unlock iphone 4 how to unlock iphone 4 how to unlock iphone 4 unlock iphone 4
_________________
unlock iphone 4 unlock iphone 4 how to unlock iphone 4 unlock iphone 4

#31 mac keyloggers on 07.11.11 at 2:30 pm

Completely I share your opinion. It is good idea. It is ready to support

you.

#32 9cabeGGce-0 on 07.12.11 at 1:35 am

hdmi to vga adapter

#33 magnetic products on 07.14.11 at 12:24 am

Best Quality Magnetic Jewelry and Magnet Therapy Products – Over 1300 Items that are good for Health as well as Beauty – Free Worldwide Shipping.

#34 best ways to quit smoking on 07.19.11 at 10:53 am

Nothing so conclusively proves a man’s ability to lead others as what he does from day to day to lead himself….

Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you can do with a few pics to drive the message home a little bit, but other than that, this is wonderful blog. An excellent read. …

Leave a Comment