Spring 基于注解的AOP使用
直接上代码
1.bena.xml配置
<!-- 配置spring创建容器时要扫描的保-->
<context:component-scan base-package="com.joyTop"></context:component-scan>
<!-- 配置spring 开启注解AOP的支持-->
<aop:aspectj-autoproxy ></aop:aspectj-autoproxy>
2.service提供注解
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
public void saveAccount()
{
//int i=1/0;
System.out.println("保存");
}
public void updateAccount(int i) {
System.out.println("更新");
}
public int deleteAccount() {
System.out.println("删除");
return 0;
}
}
- Logger提供注解
因为注解的spring前置通知、后置、异常通知、最终通知有执行顺序问题,我们建议使用注解环绕通知。已经把其余通知关闭,只开启环绕通知
//用于记录日志的工具类,它里面提供了公共的代码
@Component("logger") //交给spring容器管理
@Aspect //表示当前是一个切面
public class Logger {
//统一切入点
@Pointcut("execution(* com.joyTop.service.impl.*.*(..))")
private void pt1(){}
//用于打印日志,计划让其在切入点方法执行之前(切入点方法就是业务层方法)
public void printLog() {
System.out.println("Logger类开始记录日志");
}
//前置通知
//@Before("pt1()")
public void beforpringLog() {
System.out.println("前置通知beforpringLog类开始记录日志");
}
//后置通知
//@AfterReturning("pt1()")
public void afterReturningprintLog() {
System.out.println("后置通知afterReturningprintLog类开始记录日志");
}
//异常通知
//@AfterThrowing("pt1()")
public void afterThrowingPrintLog() {
System.out.println("异常通知afterThrowingPrintLog类开始记录日志");
}
//最终通知
//@After("pt1()")
public void afterPrintLog() {
System.out.println("最终通知afterPrintLog类开始记录日志");
}
@Around("pt1()")-------------------------------------环绕通知
public Object aroundPringLog(ProceedingJoinPoint pjp) {
Object rtValue = null;
try {
Object[] args = pjp.getArgs();//得到方法执行所需的参数
System.out.println("前置aroundPringLog环绕通知");
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("后置aroundPringLog环绕通知");
return rtValue;
} catch (Throwable t) {
System.out.println("异常aroundPringLog环绕通知");
throw new RuntimeException(t);
} finally {
System.out.println("最终aroundPringLog环绕通知");
}
}
- AOPTest测试方法
public class AOPTest {
public static void main(String[] args) {
//1.获取容器
//ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
IAccountService as = ac.getBean("accountService", IAccountService.class);
as.saveAccount();
}
}
5.运行结果
前置通知beforpringLog类开始记录日志
保存
最终通知afterPrintLog类开始记录日志
后置通知afterReturningprintLog类开始记录日志
6.Mave的引入
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8.RELEASE</version>
</dependency>
</dependencies>
7.不使用XML的配置方式
新建一个配置类
@Configuration //这是一个配置类
@ComponentScan(basePackages = "com.joyTop") //要扫描的包
@EnableAspectJAutoProxy //开启注解AOP的支持
public class SpringConfiguration {
}
测试时需要更换获取容器的类:AnnotationConfigApplicationContext
//1.获取容器
ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.获取对象
IAccountService as = ac.getBean("accountService", IAccountService.class);
as.saveAccount();