El contenido básico relacionado con IoC llega a su fin. Esta vez presento la segunda característica de Spring, AOP, programación orientada a aspectos. La terminología suena relativamente difícil de entender, no importa, todo es un ejemplo, veamos un ejemplo simple, entender.
Primer vistazo a la estructura general
Hay varias categorías en él,
Primero, pom.xml necesita hacer referencia a jar dentro,
Segundo: Defina una interfaz Hellointerface para implementar la interfaz: UserServiceImpl
Tercero: agregue un root-context.xml
Cuarto: agregar TimeMonitor de clase Aop
Quinto: clase de prueba de aplicación de primavera
El primer paso es crear una interfaz, esta es una clase normal, que no tiene nada que ver con el pensamiento aop.
Crear interfaz HelloInterface
package springaop.aopservice; public interface HelloInterface { void sayHello(); }
Paso 2: crear la clase de implementación UserServiceImpl
package springaop.aopservice.impl; import org.springframework.stereotype.Service; import springaop.aopservice.HelloInterface; @Service public class UserServiceImpl implements HelloInterface { public void sayHello() { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("userHello"); } }
Paso 3: crear root-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <context:component-scan base-package="springaop"></context:component-scan> </beans>
Paso 4: agregue pom.xml
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency>
Paso 5: agregar una clase aop
Aquí necesitas entender las 5 anotaciones de aop
Se llamará al método de notificación @after después de que el método de destino regrese o arroje una excepción
Se llamará al método de notificación @afterreturning después de regresar
Se llamará al método de notificación @AfterThrowing después de lanzar una excepción
El método de notificación @Around encapsula el método de destino, es decir, se ejecuta antes y después del método. Use Object re = pjp.proceed (); para distinguir antes y después
@Before se ejecutará el método de notificación antes de que se llame al método de destino
package springaop.aopservice.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Service; @Service @Aspect public class TimeMonitor { @Pointcut("execution(* springaop.aopservice.impl.UserServiceImpl.sayHello(..))") public void performance(){} @Around("performance()") public void monitorAround(ProceedingJoinPoint pjp) throws Throwable { System.out.println("method start time:" + System.currentTimeMillis()); Object re = pjp.proceed(); System.out.println("method end time:" + System.currentTimeMillis()); } @Before("performance()") public void tekeSeats(){ System.out.println("我来测试一下,看看能不能先执行method end time:" + System.currentTimeMillis()); } @AfterReturning("performance()") public void afterSeats(){ System.out.println("我来测试一下,看看能不能后执行method end time:" + System.currentTimeMillis()); } }
El sexto paso:
prueba
package springaop.springaop; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.support.ClassPathXmlApplicationContext; import springaop.aopservice.HelloInterface; @SpringBootTest class SpringaopApplicationTests { ///通过XMl的方式实现 aop @Test void contextLoads() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("root-context.xml"); HelloInterface userService = context.getBean(HelloInterface.class); userService.sayHello(); context.close(); } }