English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

SpringBoot AOP @Before

Antes de usar o conselho no programação orientada a aspectos, é possível realizar operações de interseção. Este é um tipo de conselho que garante que o conselho seja executado antes da execução do método. Usamos @Before Anotações para implementar o aviso before.

Vamos entender o conselho before através de um exemplo.

Exemplo de Spring Boot @Before

Passo1: Abra o Spring Initializr http://start.spring.io .

Passo2: Fornecer Group Nome. Nós fornecemos o nome do grupo com.w3codebox.

Passo3: Fornecer Artifact Id Criar um novo aop-before-advice-example.

Passo4: Adicionar Spring Web Dependência.

Passo5: Clique Gerarbotão. Quando clicamos no botão "Gerar", ele empacota todas as especificações dentro de jar do arquivo e baixá-lo para o sistema local.

Passo6: Extrairo arquivo jar baixado.

Passo7: Use os seguintes passos para importarpasta:

arquivo->Importar->Projeto Maven existente->Próximo->Navegar na pasta aop-before-advice-example ->Concluído.

Passo8: open pom.xml adicionar o seguinte ao arquivo AOP Dependências. É usado Spring AOP e AspectJ Introdução à programação 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>

Passo9: open AopBeforeAdviceExampleApplication.java file and add the annotation @EnableAspectJAutoProxy.

@EnableAspectJAutoProxy(proxyTargetClass=true)

It supports processing components marked with the AspectJ @Aspect annotation. It is used together with the @Configuration annotation. We can use proxyTargetClass property 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);
    }
}

Passo10: Crie um nome de com.w3codebox.model package.

Passo11: Pacote com.w3Create a class under codebox.model. We created a named Employee class. In the class, define the following:

define three String type variables empId, firstName,e secondName . generateGetters and Setters. createdefault

Employee.java

package com.w3codebox.model;
public class Employee 
{
    private String empId;
    private String firstName;
    private String secondName;
    //Construtor padrão
    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;
    }
}

Passo12: Crie um nome de com.w3Pacote codebox.controller.

Passo13: Pacote com.w3Crie uma classe controladora em codebox.controller. We created a named Classe EmployeeController.

No controle de classe, definimos dois mapeamentos, um para adicionar funcionários e outro para excluir funcionários.

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";
    }
}

Passo14: Crie um nome de com.w3The codebox.service package.

Passo15: Pacote com.w3Create a Service class under codebox.service. We created a named The EmployeeService class.

No Service class, we define two methods createEmployee e 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) 
    {
    
    }
}

Passo16: Crie um nome de com.w3Pacote codebox.aspect.

Passo17: Pacote com.w3Crie um classe de aspecto dentro de codebox.aspect. Criamos um nome Classe EmployeeServiceAspect.

Dentro da classe de aspecto, definimos a lógica de notificação 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étodo:" + joinPoint.getSignature());
        System.out.println("Criar nome de Employee do Employee - " + fname + ", second name - " + sname + " and id - " + empId);
    }
}

Dentro da classe acima:

Executar (expressão): Uma expressão é um método ao qual pode ser aplicado o conselho. @Before: Marca funcionalidades como conselhos a serem executados antes dos métodos cobertos pelo PointCut.

Após a criação de todos os módulos, a estrutura do diretório do projeto será como follows:

Já configuramos todos os módulos. Agora, vamos executar o aplicativo.

o18Passo: abrir e AopBeforeAdviceExampleApplication.java Arquivo e execute-o como aplicativo Java.

Passo19: Abra o navegador e chame a seguinte URL: http: //localhost: 8080/add/employee?empId = {id}&firstName = {fname}&secondName = {sname }

Na URL acima, /add/employee é o mapeamento criado na classe Controller. Usamos dois delimitadores (?)e (&)para separar os dois valores.

No output acima, atribuímos emId 101firstName = Tim,e secondName = cozinhar.

Vamos ver o console. Vemos que ao chamar EmployeeService da classe createEmployee antes de executar o método EmployeeServiceAspect método da classe beforeAdvice()como mostrado a seguir.

Da mesma forma, também podemos chamar a URL http://localhost:8080/remove/employee?empId = 101Exclua o funcionário. Ele retornará uma mensagem Despedidocomo mostrado na figura a seguir.

Nesta seção, aprendemos a consultar o trabalho anterior. Na próxima parte, vamos aprender a trabalhar com sugestões posteriores e aplicá-las na prática.