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

SpringBoot AOP @Before

Before implementing cross-cutting operations in aspect-oriented programming, we can ensure that the advice runs before the method execution. This is an advice type that ensures the advice runs before the method execution. We use @Before Annotation to implement before notification.

Let's understand the before advice through an example.

Spring Boot @Before example

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

Step2: Provide Group Name. We provide group names com.w3codebox.

Step3: Provide Artifact Id Create a new aop-before-advice-example.

Step4: Add Spring Web Dependency.

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

Step6: Extractthe downloaded jar file.

Step7: Use the following steps to importfolder:

file->Import->Existing Maven project->Next->Browse folder aop-before-advice-example ->Complete.

Step8: Open pom.xml file and add the following AOP dependency. It is used Spring AOP and AspectJ Introduction to Aspect-Oriented Programming (AOP).

<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-before-advice-example</artifactId>
<version>0.0.1-SNAPSHOT</version>  
<packaging>jar</packaging>  
<name>aop-before-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 AopBeforeAdviceExampleApplication.java file and add the annotation @EnableAspectJAutoProxy.

@EnableAspectJAutoProxy(proxyTargetClass=true)

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

AopBeforeAdviceExampleApplication.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 AopBeforeAdviceExampleApplication 
{
    public static void main(String[] args) {
    SpringApplication.run(AopBeforeAdviceExampleApplication.class, args);
    }
}

Step10: Create a name of com.w3codebox.model package.

Step11: In the package com.w3Create a class under codebox.model. We create a named Employee class. In the class, define the following:

define three String 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: In the package com.w3Create a controller class under codebox.controller. We create a named 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: Create a name of com.w3The codebox.service package.

Step15: In the package com.w3Create a Service class under codebox.service. We create a named 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: Create a name of com.w3The package codebox.aspect.

Step17: In the package com.w3Create an aspect class under codebox.aspect. We have created a named The class of EmployeeServiceAspect.

In the aspect class, we define the before notification logic.

EmployeeServiceAspect.java

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

In the above class:

Execute (expression): An expression is a method that can apply the advice. @Before: It marks the advice to be executed before the methods covered by PointCut.

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

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

The18Step: Open e AopBeforeAdviceExampleApplication.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 101firstName = Tim,and secondName = cooking.

Let's take a look at the console. We see that when calling EmployeeService class createEmployee before the () method of EmployeeServiceAspect method of the class beforeAdvice()as shown below.

Similarly, we can also call the URL http://localhost:8080/remove/employee?empId = 101Delete employee. It will return a message Resignedas shown in the figure below.

In this section, we learned about the work before consultation. In the next part, we will learn about the work after consultation and apply it in practice.