Spring Boot - Before之前

Spring Boot - Before之前 首页 / Spring Boot入门教程 / Spring Boot - Before之前

在面向切面的编程中使用Before advice,可确保advice在方法执行之前运行。无涯教程使用 @Before 注释来实施before advice。

先通过示例了解advice。

Before Advice 示例

步骤1 - 打开Spring Initializr http://start.spring.io

步骤2 - 提供 Group 名称。

步骤3 - 提供 Artifact ID。无涯教程提供了工件ID aop-bead-advice-example示例。

步骤4 - 添加 Spring Web 依赖性。

步骤5 - 单击 Generate (生成)按钮。单击"Generate"按钮时,它将所有规范包装在 jar 文件中,并将其下载到本地系统。

Spring Boot AOP Before Advice

步骤6 - 提取下载的jar文件。

步骤7 - 通过以下步骤导入文件夹:

File -> Import -> Existing Maven Projects -> Next -> Browse the Folder aop-before-advice-example -> Finish.

步骤8 - 打开 pom.xml 文件,并添加以下 AOP 依赖项。它是使用 Spring AOP AspectJ 进行面向切面编程的入门。

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

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.learnfk</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>

步骤9 - 打开 AopBeforeAdviceExampleApplication.java 文件,并添加注释 @EnableAspectJAutoProxy。

@EnableAspectJAutoProxy(proxyTargetClass=true)

它支持处理标有AspectJ的@Aspect批注的组件。它与@Configuration批注一起使用。可以使用 proxyTargetClass 属性来控制类型。其默认值为 false 

AopBeforeAdviceExampleApplication.java

package com.learnfk;
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);
  }
}

步骤10 - 创建名称为 com.learnfk.model的程序包。

步骤11  -  在包 com.learnfk.model下创建一个模型类。 无涯教程创建了一个名为 Employee的类。 在类中,定义以下内容:

  • 定义三个类型为String的变量 empId,firstName, secondName
  • 生成Getters和Setters。
  • 创建一个default构造函数

Employee.java

package com.learnfk.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;
  }
}

步骤12  - 创建一个名为 com.learnfk.controller的程序包。

步骤13  - 在包 com.learnfk.controller下创建一个控制器类。 无涯教程创建了一个名为 EmployeeController的类。

在控制器类中,定义了两个映射,一个用于添加雇员,另一个用于删除雇员。

EmployeeController.java

package com.learnfk.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.learnfk.model.Employee;
import com.learnfk.service.EmployeeService;
@RestController
public class EmployeeController 
{
  @Autowired
  private EmployeeService employeeService;
  @RequestMapping(value = "/add/employee", method = RequestMethod.GET)
  public com.learnfk.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";
  }
}

步骤14 - 创建名称为 com.learnfk.service的软件包。

步骤15  - 在包 com.learnfk.service下创建一个Service类。 无涯教程创建了一个名为 EmployeeService的类。

在Service类中,定义了两个方法 createEmployee deleteEmployee。

EmployeeService.java

package com.learnfk.service;
import org.springframework.stereotype.Service;
import com.learnfk.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) 
  {
  }
}

步骤16 - 创建名称为 com.learnfk.aspect的程序包。

步骤17  - 在包 com.learnfk.aspect下创建一个切面类。 创建了一个名为 EmployeeServiceAspect的类。

在切面类中,定义了事前通知逻辑。

EmployeeServiceAspect.java

package com.learnfk.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.learnfk.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 with first name - " + fname + ", second name - " + sname + " and id - " + empId);
  }
}

在以上类中:

  • execution(expression)  - 表达式是一种应用advice的方法。
  • @Before                              -  它将函数标记为要在PointCut涵盖的方法之前执行的advice。

创建所有模块后,项目目录如下所示:

Spring Boot AOP Before Advice

已经设置了所有模块。现在将运行该应用程序。

步骤18  - 打开e AopBeforeAdviceExampleApplication.java文件,并将其作为Java应用程序运行。

步骤19  - 打开浏览器并调用以下URL:http://localhost:8080/add/employee?empId={id}&firstName={fname}&secondName={sname}

在上面的URL中,/add /employee是在Controller类中创建的映射。无涯教程使用了两个分隔符(?)和(&)来分隔两个值。

Spring Boot AOP Before Advice

在上面的输出中,分配了 emId=101,firstName = Tim, secondName = cook。

看一下控制台。看到在调用 EmployeeService 类的 createEmployee ()方法之前, EmployeeServiceAspect 类的方法 beforeAdvice()调用,如下所示。

Spring Boot AOP Before Advice

同样,无涯教程也可以通过调用URL http:// localhost:8080/remove/employee?empId = 101来删除员工。它返回一条消息已删除员工,如下图所示。

Spring Boot AOP Before Advice

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

赵成的运维体系管理课 -〔赵成〕

深入浅出gRPC -〔李林锋〕

Go语言核心36讲 -〔郝林〕

10x程序员工作法 -〔郑晔〕

即时消息技术剖析与实战 -〔袁武林〕

React Hooks 核心原理与实战 -〔王沛〕

HarmonyOS快速入门与实战 -〔QCon+案例研习社〕

郭东白的架构课 -〔郭东白〕

徐昊 · TDD项目实战70讲 -〔徐昊〕

好记忆不如烂笔头。留下您的足迹吧 :)