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

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

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

AspectJ@Before注解用法

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

  1. @Aspect
  2. @Component
  3. public class LoggingAspect {
  4. private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
  5. @Before("execution(* net.guides.springboot2.springaop.service.EmployeeService.*(..))")
  6. public void logBeforeAllMethods(JoinPoint joinPoint) {
  7. LOGGER.debug("****LoggingAspect.logBeforeAllMethods() : " + joinPoint.getSignature().getName());
  8. }
  9. @Before("execution(* net.guides.springboot2.springaop.service.EmployeeService.getEmployeeById(..))")
  10. public void logBeforeGetEmployee(JoinPoint joinPoint) {
  11. LOGGER.debug("****LoggingAspect.logBeforeGetEmployee() : " + joinPoint.getSignature().getName());
  12. }
  13. @Before("execution(* net.guides.springboot2.springaop.service.EmployeeService.createEmployee(..))")
  14. public void logBeforeAddEmployee(JoinPoint joinPoint) {
  15. LOGGER.debug("****LoggingAspect.logBeforeCreateEmployee() : " + joinPoint.getSignature().getName());
  16. }
  17. }

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

Maven依赖项

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <project
  3. xmlns="http://maven.apache.org/POM/4.0.0"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>net.guides.springboot2</groupId>
  8. <artifactId>springboot2-springaop-example</artifactId>
  9. <version>0.0.1-SNAPSHOT</version>
  10. <packaging>jar</packaging>
  11. <name>springboot2-springaop-example</name>
  12. <description>Demo project for Spring Boot</description>
  13. <parent>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-parent</artifactId>
  16. <version>2.1.4.RELEASE</version>
  17. <relativePath />
  18. <!-- lookup parent from repository -->
  19. </parent>
  20. <properties>
  21. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  22. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  23. <java.version>1.8</java.version>
  24. </properties>
  25. <dependencies>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-aop</artifactId>
  29. </dependency>
  30. </dependencies>
  31. <build>
  32. <plugins>
  33. <plugin>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-maven-plugin</artifactId>
  36. </plugin>
  37. </plugins>
  38. </build>
  39. </project>

项目结构

以下项目结构供您参考-

创建特性-LogginAspect.java

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

  1. @Aspect
  2. @Component
  3. public class LoggingAspect {
  4. private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
  5. @Before("execution(* net.guides.springboot2.springaop.service.EmployeeService.*(..))")
  6. public void logBeforeAllMethods(JoinPoint joinPoint) {
  7. LOGGER.debug("****LoggingAspect.logBeforeAllMethods() : " + joinPoint.getSignature().getName());
  8. }
  9. @Before("execution(* net.guides.springboot2.springaop.service.EmployeeService.getEmployeeById(..))")
  10. public void logBeforeGetEmployee(JoinPoint joinPoint) {
  11. LOGGER.debug("****LoggingAspect.logBeforeGetEmployee() : " + joinPoint.getSignature().getName());
  12. }
  13. @Before("execution(* net.guides.springboot2.springaop.service.EmployeeService.createEmployee(..))")
  14. public void logBeforeAddEmployee(JoinPoint joinPoint) {
  15. LOGGER.debug("****LoggingAspect.logBeforeCreateEmployee() : " + joinPoint.getSignature().getName());
  16. }
  17. }

创建Java POJO-Employee.Java

  1. package net.guides.springboot2.springaop.model;
  2. public class Employee {
  3. private long id;
  4. private String firstName;
  5. private String lastName;
  6. private String emailId;
  7. public Employee() {
  8. }
  9. public Employee(long id, String firstName, String lastName, String emailId) {
  10. this.id = id;
  11. this.firstName = firstName;
  12. this.lastName = lastName;
  13. this.emailId = emailId;
  14. }
  15. public long getId() {
  16. return id;
  17. }
  18. public void setId(long id) {
  19. this.id = id;
  20. }
  21. public String getFirstName() {
  22. return firstName;
  23. }
  24. public void setFirstName(String firstName) {
  25. this.firstName = firstName;
  26. }
  27. public String getLastName() {
  28. return lastName;
  29. }
  30. public void setLastName(String lastName) {
  31. this.lastName = lastName;
  32. }
  33. public String getEmailId() {
  34. return emailId;
  35. }
  36. public void setEmailId(String emailId) {
  37. this.emailId = emailId;
  38. }
  39. @Override
  40. public String toString() {
  41. return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", emailId=" + emailId
  42. + "]";
  43. }
  44. }

创建服务方法-EmployeeService.java

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

  1. package net.guides.springboot2.springaop.service;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.springframework.stereotype.Service;
  5. import net.guides.springboot2.springaop.model.Employee;
  6. /**
  7. * Employee Service
  8. *
  9. * @author Ramesh
  10. *
  11. */
  12. @Service
  13. public class EmployeeService {
  14. private List < Employee > employees = new ArrayList < > ();
  15. public List < Employee > getAllEmployees() {
  16. System.out.println("Method getAllEmployees() called");
  17. return employees;
  18. }
  19. public Employee getEmployeeById(Long employeeId) {
  20. System.out.println("Method getEmployeeById() called");
  21. for (Employee employee: employees) {
  22. if (employee.getId() == Long.valueOf(employeeId)) {
  23. return employee;
  24. }
  25. }
  26. return null;
  27. }
  28. public void addEmployee(Employee employee) {
  29. System.out.println("Method addEmployee() called");
  30. employees.add(employee);
  31. }
  32. public void updateEmployee(Employee employeeDetails) {
  33. System.out.println("Method updateEmployee() called");
  34. for (Employee employee: employees) {
  35. if (employee.getId() == Long.valueOf(employeeDetails.getId())) {
  36. employees.remove(employee);
  37. employees.add(employeeDetails);
  38. }
  39. }
  40. }
  41. public void deleteEmployee(Long employeeId) {
  42. System.out.println("Method deleteEmployee() called");
  43. for (Employee employee: employees) {
  44. if (employee.getId() == Long.valueOf(employeeId)) {
  45. employees.remove(employee);
  46. }
  47. }
  48. }
  49. }

测试Spring AspectJ配置和执行

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

  1. package net.guides.springboot2.springaop;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.context.ApplicationContext;
  5. import net.guides.springboot2.springaop.model.Employee;
  6. import net.guides.springboot2.springaop.service.EmployeeService;
  7. @SpringBootApplication
  8. public class Application {
  9. public static void main(String[] args) {
  10. ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
  11. EmployeeService employeeService = applicationContext.getBean(EmployeeService.class);
  12. employeeService.addEmployee(new Employee(100 L, "ramesh", "fadatare", "ramesh@gmail.com"));
  13. employeeService.getEmployeeById(100 L);
  14. employeeService.getAllEmployees();
  15. }
  16. }

输出:

相关文章