Spring AOP示例代码
public interface CustomerDao { public void save(); public void update(); }
public class CustomerDaoImpl implements CustomerDao { public void save() { // 模拟异常 // int a = 10/0; System.out.println("保存客户..."); } public void update() { System.out.println("修改客户..."); } }
import org.aspectj.lang.ProceedingJoinPoint; /** * 切面类:切入点 + 通知 * @author Administrator */ public class MyAspectXml { /** * 通知(具体的增强) */ public void log(){ System.out.println("记录日志..."); } /** * 最终通知:方法执行成功或者出现异常,都会执行 */ public void before(){ System.out.println("before通知..."); } /** * 最终通知:方法执行成功或者出现异常,都会执行 */ public void after(){ System.out.println("after通知..."); } /** * 方法执行之后,执行后置通知。程序出现了异常,后置通知不会执行的。 */ public void afterReturn(){ System.out.println("后置通知..."); } /** * 环绕通知:方法执行之前和方法执行之后进行通知,默认的情况下,目标对象的方法不能执行的。需要手动让目标对象的方法执行 */ public void around(ProceedingJoinPoint joinPoint){ System.out.println("环绕通知1..."); try { // 手动让目标对象的方法去执行 joinPoint.proceed(); } catch (Throwable e) { e.printStackTrace(); } System.out.println("环绕通知2..."); } }
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- bean definitions here --> <!-- 配置客户的dao --> <bean id="customerDao" class="com.itheima.demo3.CustomerDaoImpl"/> <!-- 编写切面类配置好 --> <bean id="myAspectXml" class="com.itheima.demo3.MyAspectXml"/> <!-- 配置AOP --> <aop:config> <aop:aspect ref="myAspectXml"> <!-- <aop:before method="log" pointcut="execution(public void com.itheima.demo3.CustomerDaoImpl.save())"/> --> <!-- 配置最终通知 <aop:after method="after" pointcut="execution(public void com.itheima.demo3.CustomerDaoImpl.save())"/> --> <aop:before method="before" pointcut="execution(public void com.itheima.demo3.CustomerDaoImpl.save())"/> <aop:after method="after" pointcut="execution(public void com.itheima.demo3.CustomerDaoImpl.save())"/> <!-- <aop:after-returning method="afterReturn" pointcut="execution(public void com.itheima.demo3.CustomerDaoImpl.save())"/> --> <!-- 环绕通知 <aop:around method="around" pointcut="execution(public void com.itheima.demo3.CustomerDaoImpl.save())"/> --> </aop:aspect> </aop:config> </beans>