1.五个通知相关注解
@Before
@AfterReturning
@AfterThrowing
@After //相当于try-catch-finally中的final,一般用于释放资源
@Around
对应接口及说明请参考代理引入、Spring动态代理、切入点表达式、切入点函数
2.开发步骤
- 原始对象
package zyc.stu.Spring5_89_106.Service;
public interface UserService {
void register();
boolean login();
}
package zyc.stu.Spring5_89_106.Service;
public class UserServiceImpl implements UserService {
public void register() {
System.out.println("UserServiceImpl.register");
}
public boolean login() {
System.out.println("UserServiceImpl.login");
return true;
}
}
- 额外功能
- 切入点
- 组装切面
以上三部分都融入了MyAspect类中 (仅演示@Around注解)
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class MyAspect {
@Pointcut("execution(* zyc.stu.Spring5_89_106.Service.*.*(..))")
public void myPointCut(){}
@Around(value = "myPointCut()")
//等同于实现MethodInterceptor,自定义方法等同于invoke,参数ProceedingJoinPoint等同于参数MethodInvocation
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("---@Aspect log---");
return joinPoint.proceed();
}
@Around(value = "myPointCut()")
public Object around1(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("---@Aspect log1---");
return joinPoint.proceed();
}
}
配置文件中配置
<bean id="userService1" class="zyc.stu.Spring5_89_106.Service.UserServiceImpl"/>
<bean id="myAspect" class="zyc.stu.Spring5_89_106.Aspect.MyAspect"/>
<!-- 告知Spring开启注解开发 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
测试
@Test
public void test4(){
ApplicationContext context = new ClassPathXmlApplicationContext("/applicationContext2.xml");
UserService userService1 = (UserService) context.getBean("userService1");
userService1.login();
}
3.切入点复用
通过创建一个空方法,在其上使用@PointCut注解将切入点表达式提取出来,在使用时就和方法的调用一样
@Pointcut("execution(* zyc.stu.Spring5_89_106.Service.*.*(..))")
public void myPointCut(){}
4.切换动态代理方式
默认情况 AOP 编程 底层应用 JDK动态代理创建方式。
基于注解的 AOP 开发 中切换为 Cglib:
<aop:aspectj-autoproxy proxy-target-class="true"/>
传统的 AOP 开发 中切换为 Cglib:
<aop:config proxy-target-class="true">
...
</aop:config>
版权声明:本文为qq_36928041原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。