Spring基于注解的AOP配置
- 创建一个配置类,用于扫描包
@Configuration//声明配置类 @ComponentScan(basePackages = "com.lzq")//要扫描的包 @EnableAspectJAutoProxy//声明Spring开启注解AOP的支持 public class SpringConfiguration { }
- 创建一个切面类
/** * 用于记录日志的工具类,它里面提供了公共的代码 */ @Component("logger")//将该类存入Spring容器中 @Aspect//表示当前类是一个切面类 public class Logger { /** * 配置切入点表达式 */ @Pointcut("execution(* com.lzq.service.impl.*.*(..))") private void pt1(){} /** * 前置通知 */ // @Before("pt1()") public void beforePrintLog(){ System.out.println("Logger类中的beforePrintLog方法开始记录日志了...前置通知"); } /** * 后置通知 */ // @AfterReturning("pt1()") public void afterReturningPrintLog(){ System.out.println("Logger类中的afterReturningPrintLog方法开始记录日志了...后置通知"); } /** * 异常通知 */ // @AfterThrowing("pt1()") public void afterThrowingPrintLog(){ System.out.println("Logger类中的afterThrowingPrintLog方法开始记录日志了...异常通知"); } /** * 最终通知 */ // @After("pt1()") public void afterPrintLog(){ System.out.println("Logger类中的afterPrintLog方法开始记录日志了...最终通知"); } /** * 环绕通知 */ @Around("pt1()") public Object aroundPrintLog(ProceedingJoinPoint pjp){ Object rtValue = null; try { Object[] args = pjp.getArgs();//得到方法执行所需要的参数 System.out.println("Logger类中的aroundPrintLog方法开始记录日志了...前置通知"); rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法) System.out.println("Logger类中的aroundPrintLog方法开始记录日志了...后置通知"); return rtValue; } catch (Throwable throwable) { System.out.println("Logger类中的aroundPrintLog方法开始记录日志了...异常通知"); throw new RuntimeException(throwable); } finally { System.out.println("Logger类中的aroundPrintLog方法开始记录日志了...最终通知"); } } }
注意:
如果不使用环绕通知,而是分别为其配备前置通知、后置通知等等,会产生顺序错误,这个错误是Spring框架自身产生的,因此建议使用环绕通知。
- 创建业务层接口及其实现类
/** * 账户的业务层接口 */ public interface IAccountService { /** * 模拟保存账户 */ void saveAccount(); }
/** * 账户业务层的实现类 */ @Service("accountService")//将该类加入到Spring容器中 public class AccountServiceImpl implements IAccountService { @Override public void saveAccount() { // int i = 1/0; System.out.println("执行了保存..."); } }
- 创建测试类
/** * 测试AOP的配置 */ public class AOPTest { public static void main(String[] args) { //1.获取容器 ApplicationContext ac = new AnnotationConfigApplicationContext(SpringConfiguration.class); //2.获取对象 IAccountService as = (IAccountService) ac.getBean("accountService"); //3.执行方法 as.saveAccount(); } }