方法1:<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd " default-autowire="byName" > <context:annotation-config/> <context:component-scan base-package="com.daoan"/> <bean id="logIntercetor" class="com.daoan.aop.LogIntercetor"></bean> <aop:config> <!-- pointcut,在哪些方法上面加切面逻辑 --> <aop:pointcut expression="execution(public * com.daoan.service..*.add(..))" id="servicePointcut"/> <!-- 加入声明的切面对象 所参考的切面对象是logInterceptor --> <aop:aspect id="logAspect" ref="logInterceptor" > <!-- 在add方法执行之前,会先执行LogIntercetor下面的before()方法 --> <aop:before method="before" pointcut-ref="servicePointcut" /> </aop:aspect> </aop:config> </beans>
package com.daoan.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; //@Aspect //@Component public class LogIntercetor { //(在方法执行之前先执行before()方法,如果需要把该逻辑织入到某个类的某个方法上,那个对象必须是spring管理起来的) // @Before("execution(public * com.daoan.service..*.add(..))") public void before() { System.out.println("method before"); } //方法正常运行完成之后 // @Around("execution(public * com.daoan.service..*.add(..))") public void aroundMethod(ProceedingJoinPoint pjp) throws Throwable { System.out.println("method around start"); pjp.proceed(); System.out.println("method around end"); } }
方法2:
<context:annotation-config/> <context:component-scan base-package="com.daoan"/> <bean id="logIntercetor" class="com.daoan.aop.LogIntercetor"></bean> <aop:config> <!-- 加入声明的切面对象 所参考的切面对象是logInterceptor --> <aop:aspect id="logAspect" ref="logInterceptor" > <!-- 在add方法执行之前,会先执行LogIntercetor下面的before()方法 --> <aop:before method="before" pointcut="execution(public * com.daoan.service..*.add(..))" /> </aop:aspect> </aop:config>
原文地址:https://www.cnblogs.com/xdalsh/p/8440808.html
时间: 2024-10-11 06:56:51