English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Antes de implementar consejos en programación orientada a aspectos, se puede realizar una operación de cruce. Este es un tipo de consejo que asegura que el consejo se ejecute antes de que se ejecute el método. Usamos @Before Para implementar el aviso before, se utilizan anotaciones.
Vamos a entender el consejo before a través de un ejemplo.
Paso1: Abrir Spring Initializr http://start.spring.io .
Paso2: Proporcionar Grupo Nombre. Hemos proporcionado el nombre del grupo com.w3codebox.
Paso3: Proporcionar Id de Artículo Crear un nuevo aop-before-advice-ejemplo.
Paso4: Agregar Spring Web Dependencia.
Paso5: Haga clic Generarbotón. Al hacer clic en el botón "Generar", jar los archivos y descárguelos en el sistema local.
Paso6: ExtraerDescargar el archivo jar.
Paso7: Siga estos pasos para importarCarpeta:
Archivo-Importar-Proyecto Maven existente-Siguiente-Explorar carpeta aop-before-advice-ejemplo -Terminado.
Paso8: open pom.xml Agregar el siguiente archivo AOP Dependencias. Es utilizado Spring AOP y AspectJ Introducción a la programación orientada a aspectos (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>
Paso9: open AopBeforeAdviceExampleApplication.java file and add annotations @EnableAspectJAutoProxy.
@EnableAspectJAutoProxy(proxyTargetClass=true)
It supports processing components marked with AspectJ @Aspect annotation. It is used together with @Configuration annotation. We can use proxyTargetClass attribute 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); } }
Paso10: Crear un nombre de com.w3codebox.model package.
Paso11: En el paquete com.w3Create a class under codebox.model. Creamos una llamada Employee class. In the class, define the following content:
define three String type variables empId, firstName,y secondName . generateGetters and Setters. createdefault
Employee.java
package com.w3codebox.model; public class Employee { private String empId; private String firstName; private String secondName; //Constructor por defecto 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; } }
Paso12: Crear un nombre de com.w3El paquete codebox.controller.
Paso13: En el paquete com.w3Crear una clase de controlador en codebox.controller. Creamos una llamada La clase EmployeeController.
En la clase del controlador, definimos dos mapeos, uno para agregar empleados y otro para eliminar empleados.
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"; } }
Paso14: Crear un nombre de com.w3El paquete codebox.service.
Paso15: En el paquete com.w3Crea un Service clase en codebox.service. Creamos una llamada La clase EmployeeService.
En la clase Service, definimos dos métodos createEmployee y 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) { } }
Paso16: Crear un nombre de com.w3El paquete codebox.aspect.
Paso17: En el paquete com.w3Crear un clase de aspecto en codebox.aspect. Hemos creado una clase llamada La clase EmployeeServiceAspect.
En la clase de aspecto, definimos la lógica de la notificación before.
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("Antes del método:") + joinPoint.getSignature()); System.out.println("Crear nombre de Employee Employee - " + fname + ", segundo nombre - " + sname + " and id - " + empId); } }
En la clase superior:
Ejecutar (expresión): Una expresión es un método al que se puede aplicar el consejo. @Before: Marca las funcionalidades como consejos que deben ejecutarse antes de los métodos cubiertos por PointCut.
Después de crear todos los módulos, la estructura del directorio del proyecto es la siguiente:
Hemos configurado todos los módulos. Ahora, ejecutaremos la aplicación.
El18Paso: abrir e AopBeforeAdviceExampleApplication.java Archivo y ejecútelo como aplicación Java.
Paso19: Abra el navegador y llame a la siguiente URL: http: //localhost: 8080/add/employee?empId = {id}&firstName = {fname}&secondName = {sname }
en la URL superior, /add/employee es el mapeo que creamos en la clase Controller. Usamos dos delimitadores (?)y (&)para separar los dos valores.
En la salida superior, asignamos emId 101firstName = Tim,y secondName = cocinar.
Vamos a ver la consola. Vemos que al llamar EmployeeService de la clase createEmployee antes de ejecutar el método EmployeeServiceAspect método de la clase beforeAdvice()como se muestra a continuación.
Del mismo modo, también podemos llamar a la URL http://localhost:8080/remove/employee?empId = 101Eliminar empleado. Se devolverá un mensaje Despedidocomo se muestra en la siguiente figura.
En esta sección, aprendimos a consultar el trabajo anterior. En la próxima parte, aprenderemos a aplicar el trabajo posteriormente en la práctica.