English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Avant de réaliser des opérations transversales dans la programmation orientée aspect, vous pouvez réaliser des suggestions. C'est un type de suggestion qui assure que les suggestions sont exécutées avant l'exécution du méthode. Nous utilisons @Before Pour réaliser les notifications before, nous utilisons les annotations.
Commençons par un exemple pour comprendre l'avis before.
Étape1: Ouvrez Spring Initializr http://start.spring.io.
Étape2: Fournissez Groupe Nom. Nous fournissons le nom du groupe com.w3codebox.
Étape3: Fournissez Artifact Id Créez un aop-before-advice-example.
Étape4: Ajoutez Spring Web Dépendance.
Étape5: Cliquez Generatebutton. When we click the "Generate" button, it wraps all specifications in jar the file and download it to the local system.
Étape6: Extractthe downloaded jar file.
Étape7: Use the following steps to importfolder:
file->Import->Existing Maven project->Next->Browse folder aop-before-advice-example ->Completed.
Étape8: 打开 pom.xml to add the following to the file AOP dependencies. It is used Spring AOP et AspectJ Initiation for Aspect-Oriented Programming.
<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>
Étape9: 打开 AopBeforeAdviceExampleApplication.java 文件,并添加注解 @EnableAspectJAutoProxy。
@EnableAspectJAutoProxy(proxyTargetClass=true)
它支持处理带有AspectJ的@Aspect注解的组件。它与@Configuration注解一起使用。我们可以使用 proxyTargetClass 属性来控制代理的类型。其默认值为 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); } }
Étape10: Créer un nom pour com.w3codebox.model包。
Étape11: Dans le paquet com.w3在codebox.model下创建一个类。 Nous avons créé une classe nommée Employee的类。 在类中,定义以下内容:
定义三个String类型的变量 empId,firstName,et secondName 。 生成Getters and Setters。 创建default
Employee.java
package com.w3codebox.model; public class Employee { private String empId; private String firstName; private String secondName; //Constructeur par défaut 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; } }
Étape12: Créer un nom de com.w3Le paquet codebox.controller.
Étape13: Dans le paquet com.w3Créer une classe contrôleur sous codebox.controller. Nous avons créé une classe nommée La classe EmployeeController.
Dans la classe contrôleur, nous définissons deux mappings, l'un pour ajouter un employé et l'autre pour supprimer un employé.
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"; } }
Étape14: Créer un nom pour com.w3Le paquet codebox.service.
Étape15: Dans le paquet com.w3Créer un classe Service sous codebox.service. Nous avons créé une classe nommée La classe EmployeeService.
Dans la classe Service, nous définissons deux méthodes createEmployee et 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) { } }
Étape16: Créer un nom pour com.w3Le paquet codebox.aspect.
Étape17: Dans le paquet com.w3Créer un aspect dans le répertoire codebox.aspect. Nous avons créé une classe nommée La classe EmployeeServiceAspect.
Dans la classe aspect, nous avons défini la logique de notification 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("Before méthode :" + joinPoint.getSignature()); System.out.println("Créer un nom pour Employee Employee" - " + fname + ", second name - " + sname + " and id - " + empId); } }
Dans la classe suivante :
Exécuter (expression): Une expression est une méthode sur laquelle il est possible d'appliquer un conseil. @Before : Il marque les fonctionnalités comme des conseils à exécuter avant les méthodes couvertes par PointCut.
Après avoir créé tous les modules, le répertoire du projet est comme suit :
Nous avons configuré tous les modules. Maintenant, nous allons exécuter cette application.
Le18Étape : Ouvrir e AopBeforeAdviceExampleApplication.java Fichier et exécutez-le en tant qu'application Java.
Étape19: Ouvrez le navigateur et appellez l'URL suivant: http: //localhost: 8080/add/employee?empId = {id}&firstName = {fname}&secondName = {sname }
dans l'URL ci-dessus, /add/employee est la correspondance que nous avons créée dans la classe Controller. Nous avons utilisé deux séparateurs (?)et (&)pour séparer les deux valeurs.
Dans la sortie ci-dessus, nous avons assigné emId 101firstName = Tim,et secondName = cuisson.
Voyons la console. Nous voyons que lors de l'appel EmployeeService de la classe createEmployee avant la méthode () EmployeeServiceAspect méthode de la classe beforeAdvice()comme indiqué ci-dessous.
De même, nous pouvons également appeler l'URL http://localhost:8080/remove/employee?empId = 101Supprimer l'employé. Il retournera un message Désactivécomme indiqué dans l'image suivante.
Dans cette section, nous avons appris à consulter les travaux antérieurs. Dans la partie suivante, nous allons apprendre à appliquer les conseils après-coup et à les mettre en pratique.