spring四种常用通知类型
bean.xml
<?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="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean> <bean id="logger" class="com.itheima.utils.Logger"></bean> <aop:config> <aop:aspect id="logAdvice" ref="logger"> <aop:before method="beforePrintLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:before> <aop:after-returning method="afterRuturnPrintLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:after-returning> <aop:after-throwing method="afterThrowingPrintLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:after-throwing> <aop:after method="afterPrintLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:after> </aop:aspect> </aop:config> </beans>
Logger.java
package com.itheima.utils; public class Logger { /** * 前置通知 */ public void beforePrintLog() { System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。"); } /** * 后置通知 */ public void afterRuturnPrintLog() { System.out.println("后置通知Logger类中的afterRuturnPrintLog方法开始记录日志了。。。"); } /** * 异常通知 */ public void afterThrowingPrintLog() { System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了。。。"); } /** * 最终通知 */ public void afterPrintLog() { System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了。。。"); } }测试SpringTest.java
package com.itheima.test; import com.itheima.service.IAccountService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { public static void main(String[] args) { ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml"); IAccountService accountService=(IAccountService) ac.getBean("accountService"); accountService.saveAccount(); } }