English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

SpringBoot AOP @AfterThrowing

After throwing is an advice type in Spring AOP. If a method throws an exception, it ensures that the advice runs. We use @AfterThrowing Annotation to implement throwing advice.

Syntax:

@AfterThrowing(PointCut="execution(expression)  ",  throwing="name")

where:

PointCut: Select a function.

execution(expression):

throwing: The name of the exception to return.

Let's implement after in our application-throwing advice.

Spring Boot @AfterThrowing example

We will use the previous example in this section. You can download the project or make some modifications to the previous example.

Steps1: Open Spring Initializr http://start.spring.io.

Step2Step: Provide GroupName. We provide the group name com.w3codebox.

Steps3: Provide Artifact Id.Provide Artifact Id aop-after-throwing-advice-example.

Steps4: Add Spring Web Dependencies.

Steps5: click Generatebutton. When we click the "Generate" button, it wraps all specifications in jar the file and download it to the local system.

Steps6: Extract

Step7Step: ImportFolder, please follow the following steps:

File-> Import- > Existing Maven project-> Next-> Browse folder aop-throwing-advice-example -> Finish.

Steps8: Open pom.xml file, and add the following AOP Dependencies. It is used Spring AOP and AspectJ Start with the basics of aspect-oriented programming.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
build>/dependency>
build>/dependencies>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.w3codebox</groupId>
<artifactId>aop-after-throwing-advice-example/artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>aop-after-throwing-advice-example/name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
build>/parent>
<properties>
<project.build.sourceEncoding>UTF-8build>/project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8build>/project.reporting.outputEncoding>
<java.version>1.8build>/java.version>
build>/properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
build>/dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
build>/dependency>
build>/dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
build>/plugin>
build>/plugin>
build>/plugins>
build>/<

Steps9: project> In/src/main java Create a folder named com.w3codebox.model in

Steps10: in the package com.w3Create a package named Account of the class.

In the "Account" class, perform the following operations:

defined two variables of type String accountNumber and accountType . Right-click on File -> Source-> Use fields to generate a constructor Generate Getters.
Right-click on File-> Source-> Generate Getters and Setters-> Select Getters-> Generate
Generate toString()
Right-click on the file-> Source-> Generate toString()

Account.java

package com.w3codebox.model;
public class Account 
{
private String accountNumber;
private String accountType;
public Account(String accountNumber, String accountType) 
{
super();
this.accountNumber = accountNumber;
this.accountType = accountType;
}
public String getAccountType() 
{
return accountType;
}
public String getAccountNumber() 
{
return accountNumber;
}
@Override
public String toString()
{
return "Account [accountNumber=" + accountNumber+ ", accountType=" + accountType + "]";
}
}

Steps11: Create another name called com.w3codebox.service.impl package.

Steps12: In this package, create a name called AccountServiceImple class.

In this class, we define the account service.

AccountServiceImpl.Java

package com.w3codebox.service.impl;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.stereotype.Service;
import com.w3codebox.model.Account;
import org.springframework.stereotype.Service;
@Service 
{
//public class AccountServiceImpl implements AccountService
storing account detail in the HashMap
private static Map<String, Account> map = null;
{
static
//map = new HashMap<>();
adding account detail in the map4546779", new Account("10441117000", "Saving Account");
map.put("K2434567", new Account("10863554577", "Current Account");
}
@Override
public Account getAccountByCustomerId(String customerId) throws Exception
{
if (customerId == null)
{
throw new Exception("Invalid! Customer Id");
}
Account account = null;
Set<Entry<String, Account>> entrySet = map.entrySet();
for (Entry<String, Account> entry : entrySet) 
{
if (entry.getKey().equals(customerId))
{
account = entry.getValue();
}
}
return account;
}
}

Steps13: in the package com.w3codebox.service.impl. to create a name called AccountService interface.

AccountService.java

package com.w3codebox.service.impl;
import com.w3codebox.model.Account;
//creating an interface that throws an exception if the customer id is not found 
public interface AccountService 
{
public abstract Account getAccountByCustomerId(String customerId)
throws Exception;
}

Steps14: to create a name called com.w3codebox.aspect package.

Steps15: in the package com.w3codebox.aspect to create a name called AccountAspect of the class.

In this class, we implemented the after throwing advice annotation using the following method @AfterThrowing. We also defined afterThrowingAdvice()method.

Note: The name defined in the throwing attribute (ex) must correspond to the parameter name in the advice method. Otherwise, the recommendation will not run.

AccountAspect.java

package com.w3codebox.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AccountAspect 
{
//implementing after throwing advice    
@AfterThrowing(value="execution(")* com.w3codebox.service.impl.AccountServiceImpl.*(..)", throwing="ex")
public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex)
{
System.out.println("After throwing exception in method:")+joinPoint.getSignature());
System.out.println("Exception is:")+ex.getMessage());
}   
}

Steps16: Open AopAfterThrowingAdviceExampleApplication.java File and add annotation @EnableAspectJAutoProxy.

Annotation support for handling AspectJ with @Aspect Annotated component. It is used together with @Configuration annotation.

we use the @EnableAspectJAutoProxy annotation proxyTargetClass property. The property proxyTargetClass = true allows us to use CGLIB (code generation library) proxy, rather than the default JDK proxy method based on interfaces.

ConfigurableApplicationContext is an interface, which provides tools for configuring the application context in addition to the application context client methods in ApplicationContext.

AopAfterThrowingAdviceExampleApplication.java

package com.w3codebox;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import com.w3codebox.model.Account;
import com.w3codebox.service.impl.AccountService;
import com.w3codebox.service.impl.AccountServiceImpl;
@SpringBootApplication
//@EnableAspectJAutoProxy annotation supports processing components marked with @Aspect annotation. It is similar to the tag in xml configuration.
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class AopAfterThrowingAdviceExampleApplication
{
    public static void main(String[] args)  
    {
        ConfigurableApplicationContext ac = SpringApplication.run(AopAfterThrowingAdviceExampleApplication.class, args);
        //Get the account object from the application context
        AccountService accountService = ac.getBean("accountServiceImpl", AccountServiceImpl.class);
        Account account;
        try 
        {
        //Generate Exception
        account = accountService.getAccountByCustomerId(null);
        if (account != null)
            System.out.println(account.getAccountNumber());+"\t"+account.getAccountType());
        } 
        catch (Exception e) 
        {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
}

After creating all classes and packages, the project directory looks like this:

Steps17: Open AopAfterThrowingAdviceExampleApplication.java Run the file as a Java application. It displays the output as follows: