使用@Before注解的Spring AOP AspectJ Before Advice示例

x33g5p2x  于2022-10-16 转载在 Spring  
字(6.8k)|赞(0)|评价(0)|浏览(1205)

在这个Spring AOP示例中,我们将学习在基于Spring的应用程序中使用AspectJ @Before注解。我们可以使用@Before注解在一个方面中声明before-advice。
@Before注解的Before-advice方法将在连接点之前执行。除非抛出异常,否则这些方法不会阻止目标方法的执行。
在本例中,我们将创建一个简单的spring引导应用程序,添加日志方面,然后根据@Before注解中传递的切入点信息调用方面方法。

AspectJ@Before注解用法

以下代码段显示了@Before注解的用法:

@Aspect
@Component
public class LoggingAspect {

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Before("execution(* net.guides.springboot2.springaop.service.EmployeeService.*(..))")
    public void logBeforeAllMethods(JoinPoint joinPoint) {
        LOGGER.debug("****LoggingAspect.logBeforeAllMethods() : " + joinPoint.getSignature().getName());
    }

    @Before("execution(* net.guides.springboot2.springaop.service.EmployeeService.getEmployeeById(..))")
    public void logBeforeGetEmployee(JoinPoint joinPoint) {
        LOGGER.debug("****LoggingAspect.logBeforeGetEmployee() : " + joinPoint.getSignature().getName());
    }

    @Before("execution(* net.guides.springboot2.springaop.service.EmployeeService.createEmployee(..))")
    public void logBeforeAddEmployee(JoinPoint joinPoint) {
        LOGGER.debug("****LoggingAspect.logBeforeCreateEmployee() : " + joinPoint.getSignature().getName());
    }
}

让我们用一个完整的逐步示例演示@Before注解的用法。

Maven依赖项

<?xmlversion="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>net.guides.springboot2</groupId>
    <artifactId>springboot2-springaop-example</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>springboot2-springaop-example</name>
    <description>Demo project for Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.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-aop</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

项目结构

以下项目结构供您参考-

创建特性-LogginAspect.java

让我们使用基于Java的配置创建LoggingAspect。下面是一个带AspectJ注解的类和方法,其中包含切入点信息:

@Aspect
@Component
public class LoggingAspect {

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Before("execution(* net.guides.springboot2.springaop.service.EmployeeService.*(..))")
    public void logBeforeAllMethods(JoinPoint joinPoint) {
        LOGGER.debug("****LoggingAspect.logBeforeAllMethods() : " + joinPoint.getSignature().getName());
    }

    @Before("execution(* net.guides.springboot2.springaop.service.EmployeeService.getEmployeeById(..))")
    public void logBeforeGetEmployee(JoinPoint joinPoint) {
        LOGGER.debug("****LoggingAspect.logBeforeGetEmployee() : " + joinPoint.getSignature().getName());
    }

    @Before("execution(* net.guides.springboot2.springaop.service.EmployeeService.createEmployee(..))")
    public void logBeforeAddEmployee(JoinPoint joinPoint) {
        LOGGER.debug("****LoggingAspect.logBeforeCreateEmployee() : " + joinPoint.getSignature().getName());
    }
}

创建Java POJO-Employee.Java

package net.guides.springboot2.springaop.model;

public class Employee {

 private long id;
 private String firstName;
 private String lastName;
 private String emailId;
 
 public Employee() {
  
 }
 
 public Employee(long id, String firstName, String lastName, String emailId) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
  this.emailId = emailId;
 }
 
 public long getId() {
  return id;
 }
 public void setId(long id) {
  this.id = id;
 }
 
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 
 public String getEmailId() {
  return emailId;
 }
 public void setEmailId(String emailId) {
  this.emailId = emailId;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", emailId=" + emailId
    + "]";
 } 
}

创建服务方法-EmployeeService.java

让我们为Employee创建几个需要执行的方面的服务方法。

package net.guides.springboot2.springaop.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import net.guides.springboot2.springaop.model.Employee;

/**
* Employee Service
* 
* @author Ramesh
*
*/
@Service
public class EmployeeService {

    private List < Employee > employees = new ArrayList < > ();

    public List < Employee > getAllEmployees() {
        System.out.println("Method getAllEmployees() called");
        return employees;
    }

    public Employee getEmployeeById(Long employeeId) {
        System.out.println("Method getEmployeeById() called");
        for (Employee employee: employees) {
            if (employee.getId() == Long.valueOf(employeeId)) {
                return employee;
            }
        }
        return null;
    }

    public void addEmployee(Employee employee) {
        System.out.println("Method addEmployee() called");
        employees.add(employee);
    }

    public void updateEmployee(Employee employeeDetails) {
        System.out.println("Method updateEmployee() called");
        for (Employee employee: employees) {
            if (employee.getId() == Long.valueOf(employeeDetails.getId())) {
                employees.remove(employee);
                employees.add(employeeDetails);
            }
        }
    }

    public void deleteEmployee(Long employeeId) {
        System.out.println("Method deleteEmployee() called");
        for (Employee employee: employees) {
            if (employee.getId() == Long.valueOf(employeeId)) {
                employees.remove(employee);
            }
        }
    }
}

测试Spring AspectJ配置和执行

现在,让我们使用Spring boot Application测试以上配置的方面是否在给定的切入点信息上执行:

package net.guides.springboot2.springaop;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import net.guides.springboot2.springaop.model.Employee;
import net.guides.springboot2.springaop.service.EmployeeService;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
        EmployeeService employeeService = applicationContext.getBean(EmployeeService.class);
        employeeService.addEmployee(new Employee(100 L, "ramesh", "fadatare", "ramesh@gmail.com"));
        employeeService.getEmployeeById(100 L);
        employeeService.getAllEmployees();
    }
}

输出:

相关文章