The Wayback Machine - https://web.archive.org/web/20241001021209/https://www.geeksforgeeks.org/spring-aop-aspectj-annotation/
Open In App

Spring AOP – AspectJ Annotation

Last Updated : 11 Mar, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

AOP i.e Aspect-Oriented Programming complements OOP by enabling modularity of cross-cutting concerns. @AspectJ is mainly used for declaring aspects as regular Java classes annotated with annotations. Spring AspectJ AOP implementation has many annotations. They are explained below:

  • @Aspect: It declares the class as an aspect.
  • @Pointcut: It declares the pointcut expression.

Common AspectJ annotations used to create advice are as follows:

  • @Before: It runs before the method execution.
  • @AfterReturning: It runs after the result is returned by the method.
  • @AfterThrowing: It runs after an exception is thrown by the method.
  • @After(Finally): It is executed after method execution or after an exception is thrown or the result is returned by the method.
  • @Around: It can perform the behavior before and after the method invocation.
  • @Pointcut: Pointcut is a signature that matches the join points.

@Pointcut

Example of pointcut expression with before advice is as follows:

Java




// Annotation
@Before("execution(* abc.def.gettingstarted.dao.*.add(..))")
public void allMethods(Point Point)
{
  // Aspect body 
}


@Before(Before Advice)

Before advice runs before execution of target method. Before advice can access all the arguments from the Target method. It cannot alter the values of the arguments to the original method. Before advice has to specify a Pointcut expression unless we use a separate @Pointcut expression provider. 

Example: beforeAdvice() method annotated as before advice is executed before selectGetName() method is executed

Java




@Aspect
public class Logging {
  
   @PointCut("execution(* com.gfg.Student.getName(..))")
   private void selectGetName(){}
    
   @Before("selectGetName()")
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }  
    
}


@AfterReturning(After Returning Advice)

After returning advice is a normal Java method, except that we have to add @AfterReturning annotation and a Pointcut expression. The Pointcut expression maps to the signature, class, and the package of the target method, and, the advice is applied to all such matching methods.

Example: In the below example methodCall method is executed when readFile method returns something.

Java




@Slf4j
@Aspect
@Component
public class LoggingAspect {
    
    @AfterReturning("execution(* com.gfg.spring.aop.service.FileSystemStorageService.readFile(..))")
    public void methodCall(JoinPoint jp, Exception ex) {
        log.error("Target method is successfully completed!!");
    }
    
}


@AfterThrowing(After Throwing Advice)

As the name suggests, AfterThrowing advice executes when the target method throws an exception. It will not run if the method finishes successfully, or the method swallows the thrown exception. Thus, the AfterThrowing advice is useful, when we want to build a common exception handler that can catch different exceptions thrown by a different target method and takes an action.

Example: In the below example, throwingAdvice method is executed when any method of the Student class throws an exception.

Java




@AfterThrowing(PointCut = "execution(* com.gfg.Student.*(..))", throwing = "error")
public void throwingAdvice(JoinPoint jp, Throwable error){
   System.out.println("Method Signature: "  + jp.getSignature());  
   System.out.println("Exception: "+error);  
}


@After(After/Finally Advice)

An After advice runs after the target method is finished or includes when the target method results in an exception. This advice is similar to the final block in Java which always executes irrespective of the outcome.

Example: After advice is executed after method execution or after an exception is thrown or the result is returned by the method.

Java




@After("execution(* com.gfg.saop.after.dao.*.*(..))")
public void logResult(JoinPoint joinPoint)
{
    System.out.println(
        "After advice executed: "
        + joinPoint.getSignature().toShortString());
}


@Around(Around Advice)

Spring AOP supports various types of advice and the around advice is one of those pieces of advice. This advice surrounds the target method execution. That means, on a target method execution, around advice runs and calls the target method. hence, the advice gets full control over applying additional code before and after method execution. The Around advice is very popular due to its flexibility. However, Spring recommends that we should use the advice type which is the most specific according to the requirement. It performs the behavior the same as before and after advice combined.



Previous Article
Next Article

Similar Reads

Spring - AOP AspectJ Xml Configuration
Spring allows you to specify aspects, recommendations, and pointcuts in an XML file. Annotations were used in the aop examples on the preceding page. The XML configuration file will now show us the same samples. Let's look at the XML components that describe advice. aop:before: It's used before the real business logic procedure is called.aop:after:
7 min read
Spring Boot - Difference Between AOP and AspectJ
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring - AOP Example (Spring1.2 Old Style AOP)
Spring AOP allows adding additional behavior to the existing code without its modification. The Spring 1.2 Old Style AOP is supported in Spring 3 but there are a few things such as advice domain objects, that can not be done easily with Spring AOP. The AspectJ is the best available option in that case. And so, it is recommended to use Spring AOP wi
9 min read
Spring Boot - Difference Between @Service Annotation and @Repository Annotation
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. @Service Annotation In an application, the business logic resides
7 min read
Spring AOP vs Spring IOC
Spring AOPAspect Oriented Programming i.e. AOP, is another way to program a structure, similar to Object-oriented Programming (OOP). Object-oriented Programming (OOP) completely depends upon classes as the main modular unit, whereas Aspect Oriented Programming (AOP) moves the main idea to aspects. Aspects are the essential element that allows probl
4 min read
Spring Boot - Difference Between AOP and OOP
AOP(Aspect-Oriented Programming) complements OOP by enabling modularity of cross-cutting concerns. The Key unit of Modularity(breaking of code into different modules) in Aspect-Oriented Programming is Aspect. one of the major advantages of AOP is that it allows developers to concentrate on business logic. It is more convenient to use because change
3 min read
Spring Boot - AOP After Throwing Advice
Spring is widely used for creating scalable applications. For web applications Spring provides. Spring MVC is a widely used module of spring that is used to create scalable web applications. While Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also
6 min read
Spring Boot - AOP Before Advice
Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Aspects enable the implementation of crosscutting concerns such as transaction, logging not central to business logic witho
4 min read
Spring Boot - AOP After Advice
Prerequisite: Aspect Oriented Programming and AOP in Spring Framework Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Aspects enable the implementation of crosscutting con
5 min read
Spring Boot - AOP After Returning Advice
Prerequisite: Aspect Oriented Programming and AOP in Spring Framework Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Aspects enable the implementation of crosscutting con
5 min read
Spring Boot - AOP Around Advice
Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Aspects enable the implementation of crosscutting concerns such as transaction, logging not central to business logic witho
6 min read
Spring Boot - AOP(Aspect Oriented Programming)
The Java applications are developed in multiple layers, to increase security, separate business logic, persistence logic, etc. A typical Java application has three layers namely they are Web layer, the Business layer, and the Data layer. Web layer: This layer is used to provide the services to the end-user using REST API or the web application.Busi
4 min read
Usage of @Before, @After, @Around, @AfterReturning, and @AfterThrowing in a Single Spring AOP Project
Spring AOP has come up with different annotations namely @Before, @After, @Around,@AfterReturning, and @AfterThrowing. Usually, confusions occur among developers were to write the apt code among these annotations. In this article, let us see them by using a sample application. @Around This is the most effective advice among all other advice. The fi
9 min read
How to Implement AOP in Spring Boot Application?
AOP(Aspect Oriented Programming) breaks the full program into different smaller units. In numerous situations, we need to log, and audit the details as well as need to pay importance to declarative transactions, security, caching, etc., Let us see the key terminologies of AOP Aspect: It has a set of APIs for cross-cutting requirements. Logging modu
10 min read
Spring @Controller Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
4 min read
Spring - @PostConstruct and @PreDestroy Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
13 min read
Spring @Autowired Annotation
The @Autowired annotation marks a Constructor, Setter method, Properties and Config() method as to be autowired that is 'injecting beans'(Objects) at runtime by Spring Dependency Injection mechanism which is clearly depicted from the image below as shown: Enabling @Autowired annotation Spring beans can be declared either by Java configuration or XM
3 min read
Spring @Repository Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
5 min read
Spring @Service Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
4 min read
Spring Data JPA - @Table Annotation
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Spring Data JPA - @Id Annotation
Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the met
3 min read
Spring Data JPA - @Column Annotation
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
2 min read
Spring Data JPA - Attributes of @Column Annotation with Example
Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the met
3 min read
Spring @ResponseBody Annotation with Example
Spring Annotations allow us to configure dependencies and implement dependency injection through java programs. Those are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. The @ResponseBody annotation tells a c
5 min read
Spring @ComponentScan Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
4 min read
Spring - Required Annotation
Consider a scenario where a developer wants to make some of the fields as mandatory fields. using the Spring framework, a developer can use the @Required annotation to those fields by pushing the responsibility for such checking onto the container. So container must check whether those fields are being set or not. The Spring Framework supports a nu
7 min read
Spring - MVC RequestParam Annotation
@RequestParam annotation enables spring to extract input data that may be passed as a query, form data, or any arbitrary custom data. Here, we will see how we can use @RequestParam when building RESTful APIs for a web-based application. Context of the Application: Let us suppose we are implementing a sample feature for the 'Geeksforgeeks' web appli
5 min read
Spring @Bean Annotation with Example
One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. This annotation is also a part of the spring core framework. So let's understand @Bean Annotation with an
8 min read
Spring @Configuration Annotation with Example
One of the most important annotations in spring is @Configuration annotation which indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application. This annotation is part of the spring core framework. So let's understand @Configuration Annotation with an examp
4 min read
Spring @RequestMapping Annotation with Example
One of the most important annotations in spring is the @RequestMapping Annotation which is used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP requests to handler methods of controllers. When configuring Spring MVC, yo
6 min read