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

SpringBoot AOP @AfterReturning

After returningis an advice in Spring AOP, which is usually called after the join point is executed (executed). It will not be called if an exception is thrown. We can use @AfterReturning Annotation to implement the advice after the application returns. The annotation marks the function to be executed before the method covered by the PointCut.

After the advice runs back, when the matched method executes a normal return value, the advice will be executed. The name defined in the return attribute must correspond to the parameter name in the advice method. When the method returns a value, this value will be passed to the notification method as the corresponding parameter value.

Let's implement the notification after returning in the application.

SpringBoot AOP @AfterReturning

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

Steps2: provide Group Name. We provide the group name com.w3codebox.

Steps3: provides Artifact Id.Provide Artifact Id aop-after-returning-advice-example.

Steps4: add Spring Web dependencies.

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

Steps6: Extract

Step7Step: Use the following steps to importfolder:

file->Import->Existing Maven project->Next->Browsing folder aop-returning-advice-example example->Completed.

Steps8: Open pom.xml file and add the following AOP dependency. It is used to Spring AOP And AspectJ An introduction to aspect-oriented programming.

<dependency>
<plugin>/<groupId>org.springframework.boot<
groupId>-<artifactId>spring-starter-aop</plugin<
build>/scope>
build>/dependency>
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/boot-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.w3codebox</<groupId>org.springframework.boot<
<artifactId>aop-after-returning-advice-example</plugin<
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>aop-after-returning-advice-example</name>
<description>Demo project for Spring Boot</description>
<parent>
<plugin>/<groupId>org.springframework.boot<
groupId>-<artifactId>spring-starter-parent</plugin<
<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>
<plugin>/<groupId>org.springframework.boot<
groupId>-<artifactId>spring-starter-aop</plugin<
build>/scope>
<dependency>
<plugin>/<groupId>org.springframework.boot<
groupId>-<artifactId>spring-starter-test</plugin<
test</<scope>test<
build>/scope>
build>/dependency>
dependencies>
<build>
<plugins>
<plugin>/<groupId>org.springframework.boot<
groupId>-<artifactId>spring-boot-maven/plugin<
build>/artifactId>
build>/plugin>
build>/plugins>
build>/<

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

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 the file-> Source-> Use fields to generate the constructor Generate Getters.
Right-click on the 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 one named com.w3The package of codebox.service.impl.

Steps12: 在此程序包中,创建一个名称为 In this package, create a name of

AccountServiceImple class.

In this class, we define the account service.

package com.w3codebox.service.impl;
AccountServiceImpl. Java
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.w3codebox.model.Account;
import org.springframework.stereotype.Service;
@Service 
{
    //public class AccountServiceImpl implements AccountService
    Store account details in the HashMap
    private static Map<String, Account> map = null;
    {
        static
        //map = new HashMap<>();
        In the map, add account details4546779", 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 com.w3codebox.service.impl.package creates a name of AccountService interface.

AccountService.java

package com.w3codebox.service.impl;
import com.w3codebox.model.Account;
//An interface is being created, an exception is thrown if the customer id cannot be found
public interface AccountService 
{
    public abstract Account getAccountByCustomerId(String customerId) throws Exception;
}

Steps14: Create a named com.w3codebox.aspect package.

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

In this class, we use the annotation @AfterReturning. We also define afterReturningAdvice()method.

Note: We note that defined in the name(account) > returning The property must be consistent with advice methodParameters must correspond to the parameter names defined in

AccountAspect.java

package com.w3codebox.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import com.w3codebox.model.Account;
@Aspect
@Component
public class AccountAspect 
{
//implementing after returning advice   
@AfterReturning(value="execution("* com.w3codebox.service.impl.AccountServiceImpl.*(..))", returning="account")
public void afterReturningAdvice(JoinPoint joinPoint, Account account)
{
System.out.println("After Returning method:")+joinPoint.getSignature());
System.out.println(account);
}
}

Steps16: Open AopAfterReturningAdviceExampleApplication.java Add annotation to the file @EnableAspectJAutoProxy.

Annotation support for handling AspectJ with @Aspect annotation components. It is used together with the @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 that provides tools for configuring the application context in addition to the application context client methods in ApplicationContext.

AopAfterReturningAdviceExampleApplication.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
//@EnableSpectProxy annotation supports processing components marked with @Aspect annotation. It is similar to the tag in xml configuration.
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class AopAfterReturningAdviceExampleApplication
{
    public static void main(String[] args)  
    {
    ConfigurableApplicationContext ac = SpringApplication.run(AopAfterReturningAdviceExampleApplication.class, args);
    //Get the account object from the application context
    AccountService accountService = ac.getBean("accountServiceImpl", AccountServiceImpl.class);
    Account account;
    try 
    {
        account = accountService.getAccountByCustomerId("K2434567");
        if (account != null)
            System.out.println(account.getAccountNumber())+"\t"+account.getAccountType());
        } 
        catch (Exception e) 
        {
            System.out.println(e.getMessage());
        }
    }
}

After creating all classes and packages, the project directory is as follows:

Steps17: Open AopAfterReturningAdviceExampleApplication.java File and run it as a Java application. It displays the output as follows:

In the next section, we will understand after making suggestions.