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

SpringBoot AOP @After

SpringBoot AOP's After Advice is used to implement cross-cutting. This is a type of advice that ensures the advice runs after the method execution. We use @After annotations to implement post-advice.

Let's understand post-advice through an example.

SpringBoot @Around example

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

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

Step3: provides Artifact Id.Provide Artifact Id aop-after-advice-example.

Step4: add Spring Web dependencies.

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

Step6: Extractdownloaded jar file.

Step7: Import the following stepsfolder:

file->Import->Existing Maven project->Next->Browse folder aop-after-advice-example ->Completed.

Step8: Open pom.xml file and add the following AOP dependency. It is used Spring AOP and AspectJ This is an introduction to aspect-oriented programming.

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

pom.xml

<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-advice-example</artifactId>
<version>0.0.1-SNAPSHOT</version>  
<packaging>jar</packaging>  
<name>aop-after-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 -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Step9: Open AopAfterAdviceExampleApplication.java file and add annotations @EnableAspectJAutoProxy.

@EnableAspectJAutoProxy(proxyTargetClass=true)

It supports processing with AspectJ's @Aspect Component annotated with. It is used together with @Configuration annotation. We can use proxyTargetClass Attribute to control the type of proxy. Its default value is false .

AopAfterAdviceExampleApplication.java

package com.w3codebox;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@SpringBootApplication
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class AopAfterAdviceExampleApplication 
{
    public static void main(String[] args) {
        SpringApplication.run(AopAfterAdviceExampleApplication.class, args);
    }
}

Step10: 创建名称为 com.w3codebox.model package.

Step11: 在包 com.w3Create a class under codebox.model. 我们创建了一个名为 Employee class. In the class, define the following content:

Define three String type variables empId, firstName,and secondName . GenerateGetters and Setters. Createdefault

Employee.java

package com.w3codebox.model;
public class Employee 
{
    private String empId;
    private String firstName;
    private String secondName;
    //Default constructor
    public Employee() 
    {
    }
    public String getEmpId() 
    {
    return empId;
    }
    public void setEmpId(String empId) 
    {
    this.empId = empId;
    }
    public String getFirstName() 
    {
    return firstName;
    }
    public void setFirstName(String firstName) 
    {
    this.firstName = firstName;
    }
    public String getSecondName() 
    {
    return secondName;
    }
    public void setSecondName(String secondName) 
    {
    this.secondName = secondName;
    }
}

Step12: Create a name of com.w3The package of codebox.controller.

Step13: 在包 com.w3Create a controller class under codebox.controller. 我们创建了一个名为 The class of EmployeeController.

In the controller class, we define two mappings, one for adding employees and another for deleting employees.

EmployeeController.java

package com.w3codebox.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.w3codebox.model.Employee;
import com.w3codebox.service.EmployeeService;
@RestController
public class EmployeeController 
{
    @Autowired
    private EmployeeService employeeService;
    @RequestMapping(value = "/add/employee, method = RequestMethod.GET)
    public com.w3codebox.model.Employee addEmployee(@RequestParam("empId") String empId, @RequestParam("firstName") String firstName, @RequestParam("secondName") String secondName) 
    {
        return employeeService.createEmployee(empId, firstName, secondName);
    }
    @RequestMapping(value = "/remove/employee, method = RequestMethod.GET)
    public String removeEmployee(@RequestParam("empId") String empId) 
    {
        employeeService.deleteEmployee(empId);
        return "Employee removed";
    }
}

Step14: 创建名称为 com.w3The package codebox.service.

Step15: 在包 com.w3Create a Service class under codebox.service. 我们创建了一个名为 The EmployeeService class.

In the Service class, we define two methods createEmployee and deleteEmployee。

EmployeeService .java

package com.w3codebox.service;
import org.springframework.stereotype.Service;
import com.w3codebox.model.Employee;
@Service
public class EmployeeService 
{
public Employee createEmployee(String empId, String fname, String sname) 
{
Employee emp = new Employee();
emp.setEmpId(empId);
emp.setFirstName(fname);
emp.setSecondName(sname);
return emp;
}
public void deleteEmployee(String empId) 
{
}
}

Step16: 创建名称为 com.w3codebox.aspect的包。

Step17: 在包 com.w3codebox.aspect下创建一个方面类。 我们创建了一个名为 EmployeeServiceAspect的类。

在方面类中,我们定义了建议后逻辑。

EmployeeServiceAspect.java

package com.w3codebox.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class EmployeeServiceAspect 
{
    @After(value = "execution(* com.w3codebox.service.EmployeeService.*(..)) and args(empId, fname, sname)")
    public void afterAdvice(JoinPoint joinPoint, String empId, String fname, String sname) {
        System.out.println("After method:") + joinPoint.getSignature());
        System.out.println("Creating Employee with first name - " + fname + ", second name - " + sname + " and id - " + empId);
    }
}

In the above class:

execution(expression): An expression is a method that can apply advice. @After: Using @After The annotated method is executed after all methods that match the pointcut expression.

After creating all modules, the project directory is as follows:

We have set up all modules. Now we will run the application.

The18Step: Open AopAfterAdviceExampleApplication.java File and run it as a Java application.

Step19: Open the browser and call the following URL: http://localhost:8080/add/employee?empId = {id}&firstName = {fname}&secondName = {sname}

in the above URL, /add/employee is the mapping we created in the Controller class. We used two delimiters (?)and (&)to separate the two values.

In the output above, we assigned emId 102, firstName = Sachin,and secondName = Bansal.

Let's look at the console. We see that after calling EmployeeService the class createEmployee method after EmployeeServiceAspect the method of the class afterAdvice(), as shown below.

Similarly, we can also call the URL http: //localhost: 8080/remove/employee?empId = 102to delete an employee. It will return a message Discharged Employee, as shown in the figure below.

In this section, we learned the working principle of After Advice. In the next section, we will learn about the surrounding advice.