常用四种通知类型
1.业务层接口
public interface AccountService {
//模拟保存账户
void saveAccount();
//模拟更新账户
void updateAccount(int i);
//模拟删除账户
int deleteAccount();
}
2.业务层实现类
import org.springframework.stereotype.Service;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
public void saveAccount() {
System.out.println("执行了保存");
int i=1/0;
}
public void updateAccount(int i) {
System.out.println("执行了更新");
}
public int deleteAccount() {
System.out.println("执行了删除");
return 0;
}
}
3.Logger类
@Component("logger")
@Aspect//表示当前类是一个切面类
public class Logger {
@Pointcut("execution(* com.hh.service.*.*(..))")
private void pt(){}
//前置通知
@Before("pt()")
public void beforePrintLog(){
System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志");
}
//后置通知
@After("pt()")
public void afterReturnPrintLog(){
System.out.println("后置通知Logger类中的afterReturnPrintLog方法开始记录日志");
}
//异常通知
@AfterThrowing("pt()")
public void afterThrowingPrintLog(){
System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志");
}
//最终通知
@AfterReturning("pt()")
public void afterPrintLog(){
System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志");
}
}
4.配置文件
<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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置Spring创建容器时要扫描的包-->
<context:component-scan base-package="com.hh"/>
<!--配置spring开启注解的支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
5.测试类
public class AOPTest {
public static void main(String[] args) {
//获取容器
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//获取对象
AccountService accountService = context.getBean("accountService", AccountService.class);
//执行方法
accountService.saveAccount();
}
}
环绕通知
Logger类
package com.hh.utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component("logger")
@Aspect//表示当前类是一个切面类
public class Logger {
@Pointcut("execution(* com.hh.service.*.*(..))")
private void pt(){}
@Around("pt()")
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object result = null;
try {
Object[] args = pjp.getArgs();//得到方法执行的返回参数
System.out.println("Logger类中的aroundPrintLog方法开始记录日志...前置");
pjp.proceed(args);//明确调用业务层方法
System.out.println("Logger类中的aroundPrintLog方法开始记录日志...后置");
return result;
} catch (Throwable throwable) {
System.out.println("Logger类中的aroundPrintLog方法开始记录日志...异常");
throw new RuntimeException(throwable);
}finally {
System.out.println("Logger类中的aroundPrintLog方法开始记录日志...最终");
}
}
}