Spring使用注解方式实现AOP
使用注解实现实现AOP
自定义类:
AnnotationPointCut
需要增强的实现类:
UserServiceImpl
XML配置文件:
applicationContext.xml
测试类:
MyTest
1 导入一个依赖
在pom.xml文件中导入依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
2 创建类并打上注解
@Aspect
@Before
@After
@Around
创建AnnotationPointCut
package com.xzzlx.diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect // 标注这个类是一个切面
public class AnnotationPointCut {
@Before("execution(* com.xzzlx.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("*******方法执行之前********");
}
@After("execution(* com.xzzlx.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("--------方法执行之后--------");
}
/**
* 在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
* @param pjp
* @throws Throwable
*/
@Around("execution(* com.xzzlx.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前");
// 获得签名
Signature signature = pjp.getSignature();
System.out.println("signature: " + signature);
// 执行方法
Object proceed = pjp.proceed();
System.out.println("环绕后");
}
}
3 需要增强的执行类
package com.xzzlx.service;
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("这是增加");
}
@Override
public void deleted() {
System.out.println("这是删除");
}
@Override
public void update() {
System.out.println("这是更改");
}
@Override
public void select() {
System.out.println("这是查询");
}
}
4 xml文件配置
导入aop “http://www.springframework.org/schema/aop”
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="userService" class="com.xzzlx.service.UserServiceImpl"/>
<!--注解方式实现-->
<bean id="annotationPointCut" class="com.xzzlx.diy.AnnotationPointCut"/>
<!--开启注解支持-->
<aop:aspectj-autoproxy/>
</beans>
5 测试
创建测试类
import com.xzzlx.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.select();
}
}
这个是注解实现AOP,有问题可以留言一起讨论~