Spring AOP Example Tutorial – Aspect, Advice, Pointcut, JoinPoint, Annotations, XML Configuration

Filed Under: Spring
Spring Aop

Spring Framework is developed on two core concepts – Dependency Injection and Aspect Oriented Programming ( Spring AOP).

Spring AOP

We have already seen how Spring Dependency Injection works, today we will look into the core concepts of Aspect-Oriented Programming and how we can implement it using Spring Framework.

Spring AOP Overview

Most of the enterprise applications have some common crosscutting concerns that are applicable to different types of Objects and modules. Some of the common crosscutting concerns are logging, transaction management, data validation, etc.

In Object Oriented Programming, modularity of application is achieved by Classes whereas in Aspect Oriented Programming application modularity is achieved by Aspects and they are configured to cut across different classes.

Spring AOP takes out the direct dependency of crosscutting tasks from classes that we can’t achieve through normal object oriented programming model. For example, we can have a separate class for logging but again the functional classes will have to call these methods to achieve logging across the application.

Aspect Oriented Programming Core Concepts

Before we dive into the implementation of Spring AOP implementation, we should understand the core concepts of AOP.

  1. Aspect: An aspect is a class that implements enterprise application concerns that cut across multiple classes, such as transaction management. Aspects can be a normal class configured through Spring XML configuration or we can use Spring AspectJ integration to define a class as Aspect using @Aspect annotation.
  2. Join Point: A join point is a specific point in the application such as method execution, exception handling, changing object variable values, etc. In Spring AOP a join point is always the execution of a method.
  3. Advice: Advices are actions taken for a particular join point. In terms of programming, they are methods that get executed when a certain join point with matching pointcut is reached in the application. You can think of Advices as Struts2 interceptors or Servlet Filters.
  4. Pointcut: Pointcut is expressions that are matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points and Spring framework uses the AspectJ pointcut expression language.
  5. Target Object: They are the object on which advices are applied. Spring AOP is implemented using runtime proxies so this object is always a proxied object. What is means is that a subclass is created at runtime where the target method is overridden and advice are included based on their configuration.
  6. AOP proxy: 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.
  7. Weaving: It is the process of linking aspects with other objects to create the advised proxy objects. This can be done at compile time, load time or at runtime. Spring AOP performs weaving at the runtime.

AOP Advice Types

Based on the execution strategy of advice, they are of the following types.

  1. Before Advice: These advices runs before the execution of join point methods. We can use @Before annotation to mark an advice type as Before advice.
  2. After (finally) Advice: An advice that gets executed after the join point method finishes executing, whether normally or by throwing an exception. We can create after advice using @After annotation.
  3. After Returning Advice: Sometimes we want advice methods to execute only if the join point method executes normally. We can use @AfterReturning annotation to mark a method as after returning advice.
  4. After Throwing Advice: This advice gets executed only when join point method throws exception, we can use it to rollback the transaction declaratively. We use @AfterThrowing annotation for this type of advice.
  5. Around Advice: This is the most important and powerful advice. This advice surrounds the join point method and we can also choose whether to execute the join point method or not. We can write advice code that gets executed before and after the execution of the join point method. It is the responsibility of around advice to invoke the join point method and return values if the method is returning something. We use @Around annotation to create around advice methods.

The points mentioned above may sound confusing but when we will look at the implementation of Spring AOP, things will be more clear. Let’s start creating a simple Spring project with AOP implementations. Spring provides support for using AspectJ annotations to create aspects and we will be using that for simplicity. All the above AOP annotations are defined in org.aspectj.lang.annotation package.

Spring Tool Suite provides useful information about the aspects, so I would suggest you use it. If you are not familiar with STS, I would recommend you to have a look at Spring MVC Tutorial where I have explained how to use it.

Spring AOP Example

Create a new Simple Spring Maven project so that all the Spring Core libraries are included in the pom.xml files and we don’t need to include them explicitly. Our final project will look like the below image, we will look into the Spring core components and Aspect implementations in detail.

Spring AOP Example Tutorial, Spring Aspect Example

Spring AOP AspectJ Dependencies

Spring framework provides AOP support by default but since we are using AspectJ annotations for configuring aspects and advice, we would need to include them in the pom.xml file.

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">


		<!-- Generic properties -->

		<!-- Spring -->

		<!-- Logging -->

		<!-- Test -->

		<!-- AspectJ -->


		<!-- Spring and Transactions -->

		<!-- Logging with SLF4J & LogBack -->

		<!-- AspectJ dependencies -->

Notice that I have added aspectjrt and aspectjtools dependencies (version 1.7.4) in the project. Also I have updated the Spring framework version to be the latest one as of date i.e 4.0.2.RELEASE.

Model Class

Let’s create a simple java bean that we will use for our example with some additional methods.

Employee.java code:

package com.journaldev.spring.model;

import com.journaldev.spring.aspect.Loggable;

public class Employee {

	private String name;
	public String getName() {
		return name;

	public void setName(String nm) {
	public void throwException(){
		throw new RuntimeException("Dummy Exception");

Did you noticed that setName() method is annotated with Loggable annotation. It is a custom java annotation defined by us in the project. We will look into it’s usage later on.

Service Class

Let’s create a service class to work with the Employee bean.

EmployeeService.java code:

package com.journaldev.spring.service;

import com.journaldev.spring.model.Employee;

public class EmployeeService {

	private Employee employee;
	public Employee getEmployee(){
		return this.employee;
	public void setEmployee(Employee e){

I could have used Spring annotations to configure it as a Spring Component, but we will use XML based configuration in this project. EmployeeService class is very standard and just provides us an access point for Employee beans.

Spring Bean Configuration with AOP

If you are using STS, you have the option to create “Spring Bean Configuration File” and chose AOP schema namespace but if you are using some other IDE, you can simply add it in the spring bean configuration file.

My project bean configuration file looks like below.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
	xsi:schemaLocation="https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

<!-- Enable AspectJ style of Spring AOP -->
<aop:aspectj-autoproxy />

<!-- Configure Employee Bean and initialize it -->
<bean name="employee" class="com.journaldev.spring.model.Employee">
	<property name="name" value="Dummy Name"></property>

<!-- Configure EmployeeService bean -->
<bean name="employeeService" class="com.journaldev.spring.service.EmployeeService">
	<property name="employee" ref="employee"></property>

<!-- Configure Aspect Beans, without this Aspects advices wont execute -->
<bean name="employeeAspect" class="com.journaldev.spring.aspect.EmployeeAspect" />
<bean name="employeeAspectPointcut" class="com.journaldev.spring.aspect.EmployeeAspectPointcut" />
<bean name="employeeAspectJoinPoint" class="com.journaldev.spring.aspect.EmployeeAspectJoinPoint" />
<bean name="employeeAfterAspect" class="com.journaldev.spring.aspect.EmployeeAfterAspect" />
<bean name="employeeAroundAspect" class="com.journaldev.spring.aspect.EmployeeAroundAspect" />
<bean name="employeeAnnotationAspect" class="com.journaldev.spring.aspect.EmployeeAnnotationAspect" />


For using Spring AOP in Spring beans, we need to do the following:

  1. Declare AOP namespace like xmlns:aop=”https://www.springframework.org/schema/aop”
  2. Add aop:aspectj-autoproxy element to enable Spring AspectJ support with auto proxy at runtime
  3. Configure Aspect classes as other Spring beans

You can see that I have a lot of aspects defined in the spring bean configuration file, it’s time to look into them one by one.

Spring AOP Before Aspect Example

EmployeeAspect.java code:

package com.journaldev.spring.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

public class EmployeeAspect {

	@Before("execution(public String getName())")
	public void getNameAdvice(){
		System.out.println("Executing Advice on getName()");
	@Before("execution(* com.journaldev.spring.service.*.get*())")
	public void getAllAdvice(){
		System.out.println("Service method getter called");

Important points in above aspect class are:

  • Aspect classes are required to have @Aspect annotation.
  • @Before annotation is used to create Before advice
  • The string parameter passed in the @Before annotation is the Pointcut expression
  • getNameAdvice() advice will execute for any Spring Bean method with signature public String getName(). This is a very important point to remember, if we will create Employee bean using new operator the advices will not be applied. Only when we will use ApplicationContext to get the bean, advices will be applied.
  • We can use asterisk (*) as wild card in Pointcut expressions, getAllAdvice() will be applied for all the classes in com.journaldev.spring.service package whose name starts with get and doesn’t take any arguments.

We will look at the advice in action in a test class after we have looked into all the different types of advices.

Spring AOP Pointcut Methods and Reuse

Sometimes we have to use same Pointcut expression at multiple places, we can create an empty method with @Pointcut annotation and then use it as an expression in the advices.

EmployeeAspectPointcut.java code:

package com.journaldev.spring.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

public class EmployeeAspectPointcut {

	public void loggingAdvice(){
		System.out.println("Executing loggingAdvice on getName()");
	public void secondAdvice(){
		System.out.println("Executing secondAdvice on getName()");
	@Pointcut("execution(public String getName())")
	public void getNamePointcut(){}
	public void allServiceMethodsAdvice(){
		System.out.println("Before executing service method");
	//Pointcut to execute on all the methods of classes in a package
	public void allMethodsPointcut(){}

Above example is very clear, rather than expression we are using method name in the advice annotation argument.

Spring AOP JoinPoint and Advice Arguments

We can use JoinPoint as a parameter in the advice methods and using it get the method signature or the target object.

We can use args() expression in the pointcut to be applied to any method that matches the argument pattern. If we use this, then we need to use the same name in the advice method from where the argument type is determined. We can use Generic objects also in the advice arguments.

EmployeeAspectJoinPoint.java code:

package com.journaldev.spring.aspect;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

public class EmployeeAspectJoinPoint {
	@Before("execution(public void com.journaldev.spring.model..set*(*))")
	public void loggingAdvice(JoinPoint joinPoint){
		System.out.println("Before running loggingAdvice on method="+joinPoint.toString());
		System.out.println("Agruments Passed=" + Arrays.toString(joinPoint.getArgs()));

	//Advice arguments, will be applied to bean methods with single String argument
	public void logStringArguments(String name){
		System.out.println("String argument passed="+name);

Spring AOP After Advice Example

Let’s look at a simple aspect class with an example of After, After Throwing and After Returning advice.

EmployeeAfterAspect.java code:

package com.journaldev.spring.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

public class EmployeeAfterAspect {

	public void logStringArguments(String name){
		System.out.println("Running After Advice. String argument passed="+name);
	public void logExceptions(JoinPoint joinPoint){
		System.out.println("Exception thrown in Employee Method="+joinPoint.toString());
	@AfterReturning(pointcut="execution(* getName())", returning="returnString")
	public void getNameReturningAdvice(String returnString){
		System.out.println("getNameReturningAdvice executed. Returned String="+returnString);

We can use within in pointcut expression to apply the advice to all the methods in the class. We can use @AfterReturning advice to get the object returned by the advised method.
We have throwException() method in the Employee bean to showcase the use of After Throwing advice.

Spring AOP Around Aspect Example

As explained earlier, we can use Around aspect to cut the method execution before and after. We can use it to control whether the advised method will execute or not. We can also inspect the returned value and change it. This is the most powerful advice and needs to be applied properly.

EmployeeAroundAspect.java code:

package com.journaldev.spring.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

public class EmployeeAroundAspect {

	@Around("execution(* com.journaldev.spring.model.Employee.getName())")
	public Object employeeAroundAdvice(ProceedingJoinPoint proceedingJoinPoint){
		System.out.println("Before invoking getName() method");
		Object value = null;
		try {
			value = proceedingJoinPoint.proceed();
		} catch (Throwable e) {
		System.out.println("After invoking getName() method. Return value="+value);
		return value;

Around advice are always required to have ProceedingJoinPoint as an argument and we should use it’s proceed() method to invoke the target object advised method.

If advised method is returning something, it’s advice responsibility to return it to the caller program. For void methods, advice method can return null.

Since around advice cut around the advised method, we can control the input and output of the method as well as it’s execution behavior.

Spring Advice with Custom Annotation Pointcut

If you look at all the above advice pointcut expressions, there are chances that they get applied to some other beans where it’s not intended. For example, someone can define a new spring bean with getName() method and the advice will start getting applied to that even though it was not intended. That’s why we should keep the scope of pointcut expression as narrow as possible.

An alternative approach is to create a custom annotation and annotate the methods where we want the advice to be applied. This is the purpose of having Employee setName() method annotated with @Loggable annotation.

Spring Framework @Transactional annotation is a great example of this approach for Spring Transaction Management.

Loggable.java code:

package com.journaldev.spring.aspect;

public @interface Loggable {


EmployeeAnnotationAspect.java code:

package com.journaldev.spring.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

public class EmployeeAnnotationAspect {

	public void myAdvice(){
		System.out.println("Executing myAdvice!!");

The myAdvice() method will advice only setName() method. This is a very safe approach and whenever we want to apply the advice on any method, all we need is to annotate it with Loggable annotation.

Spring AOP XML Configuration

I always prefer annotation but we also have the option to configure aspects in the spring configuration file. For example, let’s say we have a class as below.

EmployeeXMLConfigAspect.java code:

package com.journaldev.spring.aspect;

import org.aspectj.lang.ProceedingJoinPoint;

public class EmployeeXMLConfigAspect {

	public Object employeeAroundAdvice(ProceedingJoinPoint proceedingJoinPoint){
		System.out.println("EmployeeXMLConfigAspect:: Before invoking getName() method");
		Object value = null;
		try {
			value = proceedingJoinPoint.proceed();
		} catch (Throwable e) {
		System.out.println("EmployeeXMLConfigAspect:: After invoking getName() method. Return value="+value);
		return value;

We can configure it by including the following configuration in the Spring Bean config file.

<bean name="employeeXMLConfigAspect" class="com.journaldev.spring.aspect.EmployeeXMLConfigAspect" />

<!-- Spring AOP XML Configuration -->
	<aop:aspect ref="employeeXMLConfigAspect" id="employeeXMLConfigAspectID" order="1">
		<aop:pointcut expression="execution(* com.journaldev.spring.model.Employee.getName())" id="getNamePointcut"/>
		<aop:around method="employeeAroundAdvice" pointcut-ref="getNamePointcut" arg-names="proceedingJoinPoint"/>

AOP xml config elements purpose is clear from their name, so I won’t go into much detail about it.

Spring AOP Example

Let’s have a simple Spring program and see how all these aspects cut through the bean methods.

SpringMain.java code:

package com.journaldev.spring.main;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.journaldev.spring.service.EmployeeService;

public class SpringMain {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
		EmployeeService employeeService = ctx.getBean("employeeService", EmployeeService.class);

Now when we execute the above program, we get the following output.

Mar 20, 2014 8:50:09 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4b9af9a9: startup date [Thu Mar 20 20:50:09 PDT 2014]; root of context hierarchy
Mar 20, 2014 8:50:09 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Service method getter called
Before executing service method
EmployeeXMLConfigAspect:: Before invoking getName() method
Executing Advice on getName()
Executing loggingAdvice on getName()
Executing secondAdvice on getName()
Before invoking getName() method
After invoking getName() method. Return value=Dummy Name
getNameReturningAdvice executed. Returned String=Dummy Name
EmployeeXMLConfigAspect:: After invoking getName() method. Return value=Dummy Name
Dummy Name
Service method getter called
Before executing service method
String argument passed=Pankaj
Before running loggingAdvice on method=execution(void com.journaldev.spring.model.Employee.setName(String))
Agruments Passed=[Pankaj]
Executing myAdvice!!
Running After Advice. String argument passed=Pankaj
Service method getter called
Before executing service method
Exception thrown in Employee Method=execution(void com.journaldev.spring.model.Employee.throwException())
Exception in thread "main" java.lang.RuntimeException: Dummy Exception
	at com.journaldev.spring.model.Employee.throwException(Employee.java:19)
	at com.journaldev.spring.model.Employee$$FastClassBySpringCGLIB$$da2dc051.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
	at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:58)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
	at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
	at com.journaldev.spring.model.Employee$$EnhancerBySpringCGLIB$$3f881964.throwException(<generated>)
	at com.journaldev.spring.main.SpringMain.main(SpringMain.java:17)

You can see that advices are getting executed one by one based on their pointcut configurations. You should configure them one by one to avoid confusion.

That’s all for Spring AOP Example Tutorial, I hope you learned the basics of AOP with Spring and can learn more from examples. Download the sample project from below link and play around with it.


  1. Seetesh says:


    Why have you configured autoproxy?

    On laptops usin mobile hotspot this doesn’t work

  2. Abhishek Patwari says:

    Thank you Pankaj, it was a really helpful , appreciate the simplicity and the effort you have put in.

  3. Ankit says:

    can we create custom annotation for class level ???
    for AOP

  4. Ankit Gupta says:

    Thanks Pankaj, the tutorial was good. Keep up the good work.

  5. Artur Semikov says:

    “Spring AOP Pointcut Methods and Reuse” – to much redundant code here. You can extract pattern of pointacat into static string (…public static final String EXECUTION_PUBLIC_STRING_GET_NAME = “execution(public String getName())”…) and reuse it everywhere bellow (…@Before(EXECUTION_PUBLIC_STRING_GET_NAME)…)

  6. Rajasekhar says:

    Hi Pankaj,

    I have one question, i.e As advice methods are printing the logs for all the method calls, i want to prevent some sensitive data one particular method returns. How can i handle this in advice method.

    1. Jed Jiang says:

      Hi Rajasekhar ,
      You can pass ProceedingJoinPoint as paramater in your Advice method and then you will get method name by calling ProceedingJoinPoint .getSignature()).getMethod() so that you can handle your particular method.

  7. shripad says:


    I was trying to load the code part of the tutorial but unfortunately in any of browser of my system is unable to the code part. I’ve inspected it is in <code> tag, may I know what configuration changes I need to maintain in order to able to see the practical example of the tutorial.

  8. elahe says:

    This was very helpful.
    Thanks a lot.

  9. Vikash singh says:

    Nice explanation …Thanks for help

  10. Daniel says:

    Hi Pankaj. Can you help me with this error?. Thanks for your effort, man.

    Exception in thread “main” org.springframework.beans.factory.BeanCreationException: Error creating bean with name ’employee’ defined in class path resource [spring.xml]: Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: error at ::0 can’t find referenced pointcut allMethodsPoincut

    Caused by: java.lang.IllegalArgumentException: error at ::0 can’t find referenced pointcut allMethodsPoincut

    1. ZeroRisk says:

      It may be too lat for you, but maybe will be helpful for others.
      I had the same problem.
      Updating aspectjtools to a later versionin the maven pom.xml solved the problem.


      For the corious see this thread:

    2. Nithin kharvi says:

      Add this dependency in pom.xml


    3. Bala says:

      It is a typo (allMethodsPoincut) error and should be like “allMethodsPointcut”.

  11. Kura says:

    This is a great tutorial and very useful explanation of core concepts

  12. Rashanand says:

    I am a beginner to AOP. Great tutorial. Thanks a lot.

  13. Vijay Pothamsetty says:

    How it is working without using “”proxy-target-class” attribute on . Which proxy above application is using.

  14. Sumit says:

    Great Tutorial. Helped me a lot.
    Thank you very much.

  15. Ravi kumar says:

    nice example sir

  16. Nishtha Mehrotra says:

    It is mentioned that “This is a very important point to remember, if we will create Employee bean using new operator the advices will not be applied. Only when we will use ApplicationContext to get the bean, advices will be applied.”

    How to apply advice on methods called using objects created using new operator?

    1. FunnyGuy says:

      It was said so as we are using spring to create objects and getters are called by default when using context.

      If we are using new operator to create objects then the method getName() has to be called manually

  17. Sushank Dahiwadkar says:

    Hi, i was unable to get the ClassPathXmlApplicationContext object using the spring version specified in the article. Then i changed to 4.3.5.RELEASE and it started working.

    Nice article and almost all the concepts got cleared about AOP.
    Thanks Pankaj.

    1. Rashanand says:

      Same happened with me also.. I used the version you mentioned and it works now. Thanks.

  18. Rafał Piotrowicz says:

    Great article. I have some question. I’m automated tester and I often create transaction methods , It mean, I create connection to database next I invoke some query and close connection and for example ResultStatment. I want to close it by annotation because it occures in many classes. The problem is that this connection and result statment is local values. It possible ?

  19. Carlos says:

    Hi, have a problem with a beans annotation…… this error is the next in the line of the “servlet-context.xml”

    the error is :

    The fully qualified name of the bean’s class, except if it serves only as a parent definition for child bean

    Please I can not find the solution and I can not make progress

  20. sandeep says:

    Hi Pankaj ,

    I using around advice on RestController but getting
    java.lang.ClassCastException: org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint cannot be cast to java.util.List

    I have in place

    Any help would be appreciated


  21. syed basit says:

    mr.pankaj can u tell me how many jar files are requried to aop..and aop and aop anannotations …

  22. Bảo Toàn says:

    Thank you so much, man 🙂
    In the future, I hope you active continue with many useful article for everyone 😀

  23. prem says:

    nice article..will you please post me that log4j with spring aop in spring boot

  24. Jaison Joseph says:

    Very good tutorial for AOP.Thankyou

  25. Gauravdeep says:

    Please Kindly allow a question on this forum. It is seen that still the stacktrace being printed even after the Aspect has already handled the exception.Can you suggest a way to clean out that.Since the exception should not leak out the AfterThrowing Aspect.

  26. dharmendra.sahu08@gmail.com says:

    very nice tutorial. It helps me a lot to understand the AOP concept.

  27. Naaveen says:

    Thanks a lot for quick and clean startup tutorial for Aop.

  28. arun joshi says:

    Hi, i am looking for Spring AOP example without the use of annotations . please share that also

  29. Binh Thanh Nguyen says:

    Thanks, nice explanation & example.

  30. vijay says:

    How to capture the details for the sub method in spring AOP.Ex: Method A calling method B and Method B calling method C.Currently it capturing the details of method A in Advice but not B&C. How to capture the submethod details.

    1. zhaojc says:

      good question.i want to know how to do it ?

  31. A. Hemarathne says:

    this was very useful. thanx a lot!!!!

  32. Nikhil says:

    ” I could have used Spring annotations to configure it as a Spring Component, but we will use XML based configuration in this project. ”

    Can you give us the link to tutorial where you have used annotations , or can you tell us here how can we use annotation.

    Are you referring to @Component or @Configuration annotations?

    Thanks a lot. very nice tutorial as usual.

    1. Pankaj says:

      Yes, the configurations done in the XML can be done using annotations. That’s what is meant by the statement.

      1. Bala says:

        Is it possible to make the above example with pure annotation support? if it does.. could you please modify the above example and share the example.

  33. vimal says:

    Once imported into eclipse IDE
    there was problem in build, that was due to the following mvn dependencies


    Just changed it to


    And it worked.
    Thanks Pankaj for good article!

  34. Benjamin Cisneros says:

    Hi Pankaj. This is an excellent tutorial.
    Only I have a question. Where do you use the SLF4J & LogBack libraries? I’m really a novice using Spring.
    Thanks for your time.

    1. Sandip says:

      SLF4J is simple logging facade for java which sits on top of any logging api / interface. So when you might want to change your logger from log4j to jdk-logger as your logger, you don’t have to change your code. SLF4J is used in Spring framework for internal logging.


  35. trinsit.w says:

    Good article! Helps me to understand AOP. Thank you!

    Merry Christmas!

  36. Nethaji T M says:

    I am writing a spring AOP utility which is pure annotation based. Am able to invoke the utility from the other components but not able to do it for the getter methods in UserProfile.

    Please help me on invoking the pointcut from the domain

    The code follows.

    public class UserProfile {

    private String firstName;
    private String lastName;

    public String getFirstName() {
    return firstName;

    public void setFirstName(String firstName) {
    this.firstName = firstName;

    public String getLastName() {
    return lastName;

    public void setLastName(String lastName) {
    this.lastName = lastName;

    @ComponentScan(basePackages = { “com.test.user.*” })
    public class UserController {
    //All controller method goes here

    public class UserApiConfiguration {


    public class InternationalizationAop {

    public InternationalizationAop() {
    System.out.println(“>>>>>>>>>>>>>>aop constructor<<<<<<<<<<<<");

    @Pointcut("execution(* com.test.user.*.UserProfile.get*(..))")
    public void getTranslatedValue() {}

    public void getTranslatedString(JoinPoint joinPoint) {

    1. Nikhil says:

      I m also getting issues in applying aspects in spring mvc application.
      Were you able to successfully run your application with @EnableWebMCV and @EnableAutoJProxy?

  37. Yuvaraj says:

    Hi, I tried to use the @Around advice to get the execution time of a method and its working fine. But can this advice be used on the methods in parallel processing.

    If i try using this advice on a method which is parallel processed more than once simulataneously, it gives issue in camel and CUT logging.

    Kindly provide ur ideas

  38. Bryan says:

    I have 2 errors:
    Description Resource Path Location Type
    The project was not built since its build path is incomplete. Cannot find the class file for java.lang.CharSequence. Fix the build path then try building this project SpringAOPExample Unknown Java Problem

    Description Resource Path Location Type
    The type java.lang.CharSequence cannot be resolved. It is indirectly referenced from required .class files EmployeeAspectPointcut.java /SpringAOPExample/src/main/java/com/journaldev/spring/aspect line 1 Java Problem


    1. Pankaj says:

      Seems like java library issue in build path

  39. Ramakrishna K.C says:

    It’s general one,

    My code is here, I’m requesting you to see the problems what I’m facing and clear my doubts.


    Ramakrishna K.C

    1. Pankaj says:

      Please provide complete stack trace, also are you sure System.out.println(shape.getCircle().getName()); is printing null, not throwing exception.

  40. Velmurugan says:

    Can I block, execution of target object method if @before throws any exception

  41. Urmila says:

    I m not getting Aop in Spring ..can u explain in easy language. rest all is very Good Explanation

  42. neha shah says:

    last three advices are not working for me

    It doeanot even enter the advice class..I have configured same as urs.

    1. Pankaj says:

      Well it’s working for me, must be some configuration issue. Are you using STS? STS clearly shows the methods where advice is getting applied.

    2. neha shah says:

      thnks they worked ..I forgot to apply @Aspect for 3 classes.

      1. neha shah says:

        I need help for learning curve for springs… can u send me few links for di, jdbc, aop, mvc.
        M a new learner for springs.Thnks in advance.


        1. Pankaj says:

          Check out the Spring category, everything u mentioned above is present there in detail with example programs and much more.

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors