Spring AOP Example – Advice

Spring AOP + AspectJ
Using AspectJ is more flexible and powerful, please refer to this tutorial – Using AspectJ annotation in Spring AOP.

Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.

In Spring AOP, 4 type of advices are supported :

  • Before advice – Run before the method execution
  • After returning advice – Run after the method returns a result
  • After throwing advice – Run after the method throws an exception
  • Around advice – Run around the method execution, combine all three advices above.

Following example show you how Spring AOP advice works.

Simple Spring example

Create a simple customer service class with few print methods for demonstration later.


package com.mkyong.customer.services;

public class CustomerService {
	private String name;
	private String url;

	public void setName(String name) {
		this.name = name;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public void printName() {
		System.out.println("Customer name : " + this.name);
	}

	public void printURL() {
		System.out.println("Customer website : " + this.url);
	}

	public void printThrowException() {
		throw new IllegalArgumentException();
	}

}

File : Spring-Customer.xml – A bean configuration file


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
		<property name="name" value="Yong Mook Kim" />
		<property name="url" value="https://mkyong.com" />
	</bean>

</beans>

Run it


package com.mkyong.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.mkyong.customer.services.CustomerService;

public class App {
	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(
				new String[] { "Spring-Customer.xml" });

		CustomerService cust = (CustomerService) appContext.getBean("customerService");

		System.out.println("*************************");
		cust.printName();
		System.out.println("*************************");
		cust.printURL();
		System.out.println("*************************");
		try {
			cust.printThrowException();
		} catch (Exception e) {

		}

	}
}

Output


*************************
Customer name : Yong Mook Kim
*************************
Customer website : https://mkyong.com
*************************

A simple Spring project to DI a bean and output some Strings.

Spring AOP Advices

Now, attach Spring AOP advices to above customer service.

1. Before advice

It will execute before the method execution. Create a class which implements MethodBeforeAdvice interface.


package com.mkyong.aop;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;

public class HijackBeforeMethod implements MethodBeforeAdvice
{
	@Override
	public void before(Method method, Object[] args, Object target)
		throws Throwable {
	        System.out.println("HijackBeforeMethod : Before method hijacked!");
	}
}

In bean configuration file (Spring-Customer.xml), create a bean for HijackBeforeMethod class , and a new proxy object named ‘customerServiceProxy‘.

  • ‘target’ – Define which bean you want to hijack.
  • ‘interceptorNames’ – Define which class (advice) you want to apply on this proxy /target object.

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
		<property name="name" value="Yong Mook Kim" />
		<property name="url" value="https://mkyong.com" />
	</bean>

	<bean id="hijackBeforeMethodBean" class="com.mkyong.aop.HijackBeforeMethod" />

	<bean id="customerServiceProxy" 
                 class="org.springframework.aop.framework.ProxyFactoryBean">

		<property name="target" ref="customerService" />

		<property name="interceptorNames">
			<list>
				<value>hijackBeforeMethodBean</value>
			</list>
		</property>
	</bean>
</beans>
Note
To use Spring proxy, you need to add CGLIB2 library. Add below in Maven pom.xml file.


	<dependency>
		<groupId>cglib</groupId>
		<artifactId>cglib</artifactId>
		<version>2.2.2</version>
	</dependency>

Run it again, now you get the new customerServiceProxybean instead of the original customerService bean.


package com.mkyong.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mkyong.customer.services.CustomerService;

public class App {
	public static void main(String[] args) {
		ApplicationContext appContext = new ClassPathXmlApplicationContext(
				new String[] { "Spring-Customer.xml" });

		CustomerService cust = 
                                (CustomerService) appContext.getBean("customerServiceProxy");

		System.out.println("*************************");
		cust.printName();
		System.out.println("*************************");
		cust.printURL();
		System.out.println("*************************");
		try {
			cust.printThrowException();
		} catch (Exception e) {

		}

	}
}

Output


*************************
HijackBeforeMethod : Before method hijacked!
Customer name : Yong Mook Kim
*************************
HijackBeforeMethod : Before method hijacked!
Customer website : https://mkyong.com
*************************
HijackBeforeMethod : Before method hijacked!

It will run the HijackBeforeMethod’s before() method, before every customerService’s methods are execute.

2. After returning advice

It will execute after the method is returned a result. Create a class which implements AfterReturningAdvice interface.


package com.mkyong.aop;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;

public class HijackAfterMethod implements AfterReturningAdvice
{
	@Override
	public void afterReturning(Object returnValue, Method method,
		Object[] args, Object target) throws Throwable {
	        System.out.println("HijackAfterMethod : After method hijacked!");
	}
}

Bean configuration file


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
		<property name="name" value="Yong Mook Kim" />
		<property name="url" value="https://mkyong.com" />
	</bean>

	<bean id="hijackAfterMethodBean" class="com.mkyong.aop.HijackAfterMethod" />

	<bean id="customerServiceProxy" 
                class="org.springframework.aop.framework.ProxyFactoryBean">

		<property name="target" ref="customerService" />

		<property name="interceptorNames">
			<list>
				<value>hijackAfterMethodBean</value>
			</list>
		</property>
	</bean>
</beans>

Run it again, Output


*************************
Customer name : Yong Mook Kim
HijackAfterMethod : After method hijacked!
*************************
Customer website : https://mkyong.com
HijackAfterMethod : After method hijacked!
*************************

It will run the HijackAfterMethod’s afterReturning() method, after every customerService’s methods that are returned result.

3. After throwing advice

It will execute after the method throws an exception. Create a class which implements ThrowsAdvice interface, and create a afterThrowing method to hijack the IllegalArgumentException exception.


package com.mkyong.aop;

import org.springframework.aop.ThrowsAdvice;

public class HijackThrowException implements ThrowsAdvice {
	public void afterThrowing(IllegalArgumentException e) throws Throwable {
		System.out.println("HijackThrowException : Throw exception hijacked!");
	}
}

Bean configuration file


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
		<property name="name" value="Yong Mook Kim" />
		<property name="url" value="https://mkyong.com" />
	</bean>

	<bean id="hijackThrowExceptionBean" class="com.mkyong.aop.HijackThrowException" />

	<bean id="customerServiceProxy" 
                 class="org.springframework.aop.framework.ProxyFactoryBean">

		<property name="target" ref="customerService" />

		<property name="interceptorNames">
			<list>
				<value>hijackThrowExceptionBean</value>
			</list>
		</property>
	</bean>
</beans>

Run it again, output


*************************
Customer name : Yong Mook Kim
*************************
Customer website : https://mkyong.com
*************************
HijackThrowException : Throw exception hijacked!

It will run the HijackThrowException’s afterThrowing() method, if customerService’s methods throw an exception.

4. Around advice

It combines all three advices above, and execute during method execution. Create a class which implements MethodInterceptor interface. You have to call the “methodInvocation.proceed();” to proceed on the original method execution, else the original method will not execute.


package com.mkyong.aop;

import java.util.Arrays;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class HijackAroundMethod implements MethodInterceptor {
	@Override
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {

		System.out.println("Method name : "
				+ methodInvocation.getMethod().getName());
		System.out.println("Method arguments : "
				+ Arrays.toString(methodInvocation.getArguments()));

		// same with MethodBeforeAdvice
		System.out.println("HijackAroundMethod : Before method hijacked!");

		try {
			// proceed to original method call
			Object result = methodInvocation.proceed();

			// same with AfterReturningAdvice
			System.out.println("HijackAroundMethod : Before after hijacked!");

			return result;

		} catch (IllegalArgumentException e) {
			// same with ThrowsAdvice
			System.out.println("HijackAroundMethod : Throw exception hijacked!");
			throw e;
		}
	}
}

Bean configuration file


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="customerService" class="com.mkyong.customer.services.CustomerService">
		<property name="name" value="Yong Mook Kim" />
		<property name="url" value="https://mkyong.com" />
	</bean>

	<bean id="hijackAroundMethodBean" class="com.mkyong.aop.HijackAroundMethod" />

	<bean id="customerServiceProxy" 
                class="org.springframework.aop.framework.ProxyFactoryBean">

		<property name="target" ref="customerService" />

		<property name="interceptorNames">
			<list>
				<value>hijackAroundMethodBean</value>
			</list>
		</property>
	</bean>
</beans>

Run it again, output


*************************
Method name : printName
Method arguments : []
HijackAroundMethod : Before method hijacked!
Customer name : Yong Mook Kim
HijackAroundMethod : Before after hijacked!
*************************
Method name : printURL
Method arguments : []
HijackAroundMethod : Before method hijacked!
Customer website : https://mkyong.com
HijackAroundMethod : Before after hijacked!
*************************
Method name : printThrowException
Method arguments : []
HijackAroundMethod : Before method hijacked!
HijackAroundMethod : Throw exception hijacked!

It will run the HijackAroundMethod’s invoke()method, after every customerService’s method execution.

Conclusion

Most of the Spring developers are just implements the ‘Around advice ‘, since it can apply all the advice type, but a better practice should choose the most suitable advice type to satisfy the requirements.

Pointcut
In this example, all the methods in a customer service class are intercepted (advice) automatically. But for most cases, you may need to use Pointcut and Advisor to intercept a method via it’s method name.

Download Source Code

Download it – Spring-AOP-Advice-Examples.zip (8 KB)

122 comments on “Spring AOP Example – Advice

  1. Is it possible to register the interception without using the xml? For example when creating the application context programmatically?

    Reply
  2. Thx for this post. I’ve implemented aop for logging every call to repositories methods. Every repository interface of my app extends JpaRepository, so what would be the best strategy for log my repository interface name ?I mean,i want to log myrepository.findbyone() not crudrepository.findbyone()

    Thanks in advance!!
    Spree

    Reply
  3. Hi Yong,
    Could you take a look of jbeanbox project? it’s a simplest IOC/AOP tool (only 1 Java file) ~350 lines source codes do all the IOC/AOP job like spring core did. use Java classes as the substitute of XML, no annotation used. tks.

    Reply
  4. Hi, Example worked when running from main, i am using restful webservice where i need to intercept services like CustomerService which you have defined. Problem is how to invoke ?
    for example i have
    @Autowired CustomerService customerService;

    and
    customerService.printName();
    in one of method
    in this case it will not intercept the method.
    Any Solution?

    Reply
  5. My program does nor recognize the class ProxyFactoryBean ??

    Reply
  6. Nice Explanation it’s good for me

    Thanks

    Reply
  7. Nice example. Simple and to-the-point. Helped me to get started on AOP.

    Reply
  8. I did not add cglib dependency in my pom but all the examples on this page worked for me. Can anyone explainthe role of cglib why all examples worked without cglib? thanks in advance.

    Reply
    1. Spring AOP implementation uses JDK dynamic proxy to create the Proxy classes with target classes and advice invocations, these are called AOP proxy classes. We can also use CGLIB proxy by adding it as the dependency in the Spring AOP project.

      Reply
  9. The messaje in the Around advice example of the After method Hijacked is wrong! (Before after hijacked? :P)

    Reply
  10. Thanks….Examples are superb and easy to understand.

    Reply
  11. Great example but it is not woring in my project. The interceptors are not being executed.

    Reply
  12. The example is really simple yet effective. But I would like to know is there any way to only call the proxy for a specific method of the service class ?

    In this case, what if I want to call the proxy method only before printURL method and not for other methods. How would that be doable ?

    Reply
  13. Really Adorable… Thanks for your service and effort…

    Reply
  14. This is a very clear cut explanation , can you also explain the same using @Autowire annotation?

    Reply
  15. Hi mkyong,
    This example is not working in Spring 3.0.5 properly

    Reply
  16. Why you not used namespace ?
    xmlns:aop=”http://www.springframework.org/schema/aop”

    Reply
  17. It’s a very good example for the AOP beginers

    Thanks and Regards,
    suresh kumar. somarouthu

    Reply
  18. Example was nice but I still get that java.lang.ClassCastException: $Proxy0 error. Anybody got past this issue? how?

    Mr Mkyong, any suggestion please?

    Reply
  19. Example was nice, but I still get that java.lang.ClassCastException: $Proxy0 exception. Anybody get rid of this issue yet?
    Mr Mkyong, any suggestion please?

    Reply
  20. Thank you, this is really nice.
    Quite simple and straightforward explanation to understand for new person. Thank you again.

    Reply
  21. Hello,

    I am a french student, beginner with Spring AOP Advice.

    This article is very simple and usefull. However, I would like to know how to do when (for example) CustomerService extends a class which has got an Interface ?

    I have the following error :
    “Exception in thread “main” java.lang.ClassCastException: $Proxy0 cannot be cast to com.mkyong.customer.services.CustomerService at com.mkyong.common.App.main(App.java:14)”

    Thank you for your help 🙂

    Have a nice day,

    Regards,

    Nathan

    Reply
    1. I am getting the same error.How did you solve $proxy error0(classcastexception)

      Reply
  22. The most concise and simplest AOP examples to be found on the web. Thanks!

    One minor update: the ThrowsAdvice interface seems to have become no-op in Spring 2.5.5:

    // Compiled from ThrowsAdvice.java (version 1.4 : 48.0, no super bit)
    public abstract interface org.springframework.aop.ThrowsAdvice extends org.springframework.aop.AfterAdvice {
    }

    Reply
  23. Really superb article for beginners like me. It is simply crystal clear and very meaningful. Thanks.

    Reply
  24. Its Great. Good article.
    But I tried the same but it is not taking beforemethodadvice… I added cglib jar file in build path.. But only thing is @override annotation in HijackBeforeAdvice is throwing me compilation error.. If I remove that, compilation error goes off but NOT RUNNING the HijackBeforeMethod’s before() method.

    Can anyone please help me in this regard…I get simple output not the advice output..

    Pleaazzzzz

    Reply
    1. which JVM version are you using? it should be 1.5 or above.

      Reply
  25. Its Great. Good article.
    But I tried the same but it is not taking beforemethodadvice… I added cglib jar file in build path.. But only thing is @override annotation in HijackBeforeAdvice is throwing me compilation error.. If I remove that, compilation error goes off but NOT RUNNING the HijackBeforeMethod’s before() method.

    Can anyone please help me in this regard…I get simple output not the advice output..

    Pleaazzzzz

    Reply
    1. I added aopalliance 1.0 jar to my build path and this error went away

      Reply
      1. Hi Colin,
        I am not getting any compilation error. But while running, I am getting the below exception. I am using the main program name as MainApp.java. Rest of the info are same as in this article. I have already added aopalliance jar to the buildpath. I am using eclipse.

        Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘customerServiceProxy’: FactoryBean threw exception on object creation; nested exception is java.lang.IncompatibleClassChangeError: org.springframework.asm.ClassVisitor
        at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:149)
        at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:102)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1454)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:249)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
        at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1117)
        at com.tutorialspoint.MainApp.main(MainApp.java:13)

        Thanks in Advance
        Jagan

        Reply
        1. Where u able to find the solution for the above problem? I am also facing the same error

          Reply
          1. Please verify – the specific version of CGLIB compatible with Spring 3.1.2 is cglib 2.2.2 , asm 3.3.1, removing cglib-3.0 should just do it

      2. I also used that mentioned jar but still facing the same issue.
        Please tell me where to save “Spring-Customer.xml”
        I dont know how spring will find this Spring-Customer.xml in resource folder.
        Please help me.

        Reply
  26. This example has set the foundation for me. It’s so simple and that’s all I needed to get started in AOP. I can now start to look more in depth at AOP.

    Fantastic work, keep it up.

    Regards

    Ravi

    Reply
  27. I’m using Spring 3.1.2 and all my controllers are annotation driven. My spring context xml will not have any beans defines in that. How to achieve AOP in that case. i.e., is it possible to achieve AOP through annotations(not AspectJ though). Is it possible? If so, please let me know.

    Reply
  28. Hi,
    The example is nice. I am yet to read in depth about AOP but am wondering whether the AOP can be selective on methods. For ex, assuming a class has n methods in it and I want certain things to take place only when x methods are invoked (x<n) and for the remaining (n-x) methods, nothing should happen (no AOP behavior). Please let me know if this is something which is possible?

    Regards,
    Ramakant

    Reply
    1. Yes , that is what mkYong mentionned in the end of the tutorial.refer to the next tutorial about Pointcut and Adviser

      Reply
  29. This is very Helpfull to a beginer and best practise..
    Thanks a lot ….

    Reply
  30. Hi,

    My application context is:

    <bean id="hijackAroundMethodBean" class="org.poc.aspect.BusinessProfiler" />
    	
    	<bean id="serviceProxy" 
                    class="org.springframework.aop.framework.ProxyFactoryBean">
     
    		<property name="target" ref="serviceImpl" />
     
    		<property name="interceptorNames">
    			<list>
    				<value>hijackAroundMethodBean</value>
    			</list>
    		</property>
    	</bean>
    

    This refers to my service bean which is declared using @Qualifier annotation in my controller class. Hence there is no bean entry with this id in application context.
    No error is thrown but spring aop feature is not working.
    Please suggest a workaround.

    Reply
    1. ***** Updating my post below ******

      In my web project, my service bean is declares as follows:

      @Controller
      public class MyController(){
      
      @Qualifier("serviceImpl")
      @Autowire
      Service service;
      
      /*-- remaining code here */
      
      

      }

      Reply
  31. Clear and simple like all the other spring demo.
    Dude seriously, thank you for your work :). I’m sure it’ll help a lot of beginer

    Reply
  32. Hi
    I am getting a syntax error says
    The hierarchy of the type Hijack BeforeMethod is inconsistent
    at
    public class HijackBeforeMethod implements MethodBeforeAdvice{.

    what could be wrong??

    Reply
      1. hi friend i feel same error that
        I am getting a syntax error says
        The hierarchy of the type Hijack BeforeMethod is inconsistent
        at
        public class HijackBeforeMethod implements MethodBeforeAdvice{.

        how and where to add AOP Allianc API 1.0.0 and from where it download
        step by step
        plz answer me

        Reply
    1. hi,
      i am trying to add a DAO class to capture performance details of dao method.
      i am running thru Junit but getting exception as:
      spring autowiring with unique beans: Spring expected single matching bean but found 2

      fyi, i have defined dao once already before adding it to the advice
      Please let me know why
      thanks
      indra

      Reply
  33. Simply awesome tutorial! Finally somebody who dared to state, that AOP is not about some magic (layers, aspects, self-thinking beans, etc.), but simply about intercepting methods. That greatly clarifies things and is understandable even for beginners. And full code examples (not just snippets) help to find yourself in the convoluted world of xml configuration 🙂
    Thank you very much for this and all the other tutorials!

    Reply
  34. Simply awesome, congrats man, this is how one should be serving back to community…keep it up.

    Reply
  35. Excellent tutorial…, Its help full or every beginners.

    Reply
  36. Thank you for posting such a wonderful article.It made concepts clear.

    Reply
  37. I have read the Spring AOP before but my understanding was never clear until now.
    Excellent tutorials!!

    Reply
  38. Fantastic… Simple n effective

    Thanks a lot.

    I was about to give up learning AOP before i read this one, cause articles on many other sites make it look like rocket science :).

    Thank you

    Reply
  39. Found very Useful Information !! With Sweet and Short Example about AOP Thanks mkyong …

    Reply
  40. Really it is great tutorial for anyone so i would like to thanks mr. mkyoung for making such type of tutorial..

    Reply
  41. Hi Yong,
    It’s really Great tutorial for the beginners like me. I have used around advisor. while using it with Transformer it gives me following error.

    Caused by: org.springframework.integration.MessageHandlingException: org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 8): Method call: Method transform(org.springframework.util.LinkedCaseInsensitiveMap) cannot be found on $Proxy40 type
    at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:76)
    at org.springframework.integration.transformer.AbstractMessageProcessingTransformer.transform(AbstractMessageProcessingTransformer.java:56)
    at org.springframework.integration.transformer.MessageTransformingHandler.handleRequestMessage(MessageTransformingHandler.java:67)
    … 64 more
    Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 8): Method call: Method transform(org.springframework.util.LinkedCaseInsensitiveMap) cannot be found on $Proxy40 type
    at org.springframework.expression.spel.ast.MethodReference.findAccessorForMethod(MethodReference.java:185)
    at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:107)
    at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:57)
    at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:102)
    at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:102)
    at org.springframework.integration.util.AbstractExpressionEvaluator.evaluateExpression(AbstractExpressionEvaluator.java:126)
    at org.springframework.integration.util.MessagingMethodInvokerHelper.processInternal(MessagingMethodInvokerHelper.java:225)
    at org.springframework.integration.util.MessagingMethodInvokerHelper.process(MessagingMethodInvokerHelper.java:125)
    at org.springframework.integration.handler.MethodInvokingMessageProcessor.processMessage(MethodInvokingMessageProcessor.java:73)
    … 66 more

    Reply
  42. very excellent tutorial to understand AOP basic concept. Mkyong you got talent to simplify a complex topic. Keep it up !!

    Best wishes from Malaysia
    Zys

    Reply
  43. Young,

    I am slightly confuse about the method “invoke” when i implemented MethodInterceptor in AroundAdvice. Because there is no such method “invoke” in MethodInterceptor.

    please provide your comment on this .

    thanks
    -Roop

    Reply
    1. Roop,

      Please note

       
      import org.aopalliance.intercept.MethodInterceptor;
      import org.aopalliance.intercept.MethodInvocation;
      

      You can find MethodInterceptor in aopalliance-1.0.jar ; make sure you have this jar in classpath

      Reply
  44. Hi,

    Please explain each of these three paramters of ‘before’:

    public void before(Method method, Object[] args, Object target)

    and why
    hijackBeforeMethodBean
    value tag is used here not ref,it will be stored as string

    Reply
  45. Really Excellent Practical Example for newbies in Spring to get started with AOP.

    Simply Hats off!! for making it so simple

    Reply
  46. Please upload examples of Spring AspectJ with annotations as they are much simpler and cleaner.

    Reply
  47. Itz amazing tutorial and very simple approach to deal wid AOP..as i am unable to undersatnd concept of AOP

    Reply
  48. Very Good Tutorial. I like it. Very helpful for me to learn AOP basic concept.

    Reply
  49. I am getting the error while creating the ProxyFactoryBean itself in my AOP example.

    please tell me that whether i miss any jars ,The error is as follows,

    Caused by: java.lang.IllegalAccessError
    	at net.sf.cglib.core.ClassEmitter.setTarget(ClassEmitter.java:47)
    	at net.sf.cglib.core.ClassEmitter.(ClassEmitter.java:39)
    	at net.sf.cglib.core.KeyFactory$Generator.generateClass(KeyFactory.java:165)
    	at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    	at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:215)
    	at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:145)
    	at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:117)
    	at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
    	at net.sf.cglib.proxy.Enhancer.(Enhancer.java:64)
    	at org.springframework.aop.framework.Cglib2AopProxy.createEnhancer(Cglib2AopProxy.java:229)
    	at org.springframework.aop.framework.Cglib2AopProxy.getProxy(Cglib2AopProxy.java:171)
    	... 9 more
    
    Reply
    1. Hi Please put the cglib-2.2.jar and asm-3.1.jar into your class path.

      Reply
  50. great tutorial made my life very easy . trying to understand AOP for the past four days reading the entire spring material couldnt understand. But this one easy and simple . gGreat help thanks

    Reply
  51. Very very good tutorial,this is very small but it gives basic working of advices .
    Brilliant Work

    Reply
  52. Hi,

    It’s a great tutorial. It was very helpful. Simple and easy to understand. Great work. You saved me from slogging for hours. I was searching for materials like this.

    Once I gain sufficient knowledge about Springs, I would let you know more..

    Best wishes from India,

    -Krishna.

    Reply
  53. Best AOP tutorial I have read so far. Great example with simple explaination. Great Job!!

    Reply
  54. I read may other tutorials, but had hard time understanding AOP.
    This step by step approach made it very easy to understand.
    Thanks. Glad that I found mkyong’s tutorial.

    Reply
  55. Great tutorial.. well done.. even i didnot found in Interface 21 site also

    Hands off!!!!

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *