(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:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p" 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-3.2.xsd"> </beans>(2)将增强类转换为Bean的增强类
public class UserServiceLogger { private static Logger log = Logger.getLogger(UserServiceLogger.class); //前置增强 JoinPoint:目标方法的类名 方法名 参数列表... public void before(JoinPoint jp) { log.info("调用 " + jp.getTarget() + " 的 " + jp.getSignature(). getName() + " 方法。方法入参:" + Arrays.toString(jp.getArgs())); } //后置增强 JoinPoint:目标方法的类名 方法名 参数列表... //result 获取目标 方法的返回值 public void afterReturning(JoinPoint jp, Object result) { log.info("调用 " + jp.getTarget() + " 的 " + jp.getSignature(). getName() + " 方法。方法返回值:" + result); } }增强类
<!--增强类--> <bean id="userServiceLogger" class="org.westos.demo.aop.UserServiceLogger"> </bean>(3)配制文件:Application.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" xmlns:p="http://www.springframework.org/schema/p" 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-3.2.xsd"> <!--增强类--> <bean id="userServiceLogger" class="com.xk.demo.aop.UserServiceLogger"></bean> <!--切入点 规则 public * addNewUser(entity.User): “*”表示匹配所有类型的返回值。 public void *(entity.User): “*”表示匹配所有方法名。 public void addNewUser(..): “..”表示匹配所有参数个数和类型。 * com.service.*.*(..):匹配com.service包下所有类的所有方法。 * com.service..*.*(..):匹配com.service包及其子包下所有类的所有方法--> <!--切面--> <aop:config> <!--切入点:PointCut--> <!--expression="execution(访问修饰符 返回值类型 方法名( 包名.类名( 参数 ) ))" --> <!-- .. 任何参数 --> <!-- org.westos.demo.service.*.* 第一个* 表示所有类 第二个*所有方法 --> <aop:pointcut id="pointcut" expression="execution(* org.westos.demo.service.*.*(..))"/> <!-- 可以有很多个增强类 使用哪一个增强类 增强取决于 aop:aspect ref ="bean id"--> <aop:aspect ref="userServiceLogger"> <!-- aop:before: 固定格式 前置增强 --> <!-- method 方法名称 (来自增强类) --> <!-- pointcut-ref 切入点名称 aop:pointcut id="pointcut" --> <aop:before method="before" pointcut-ref="pointcut"></aop:before> <!-- aop:after-returning: 固定格式 后置增强 --> <!-- method 方法名称 (来自增强类) --> <!-- pointcut-ref 切入点名称 aop:pointcut id="pointcut" --> <!-- returning 有返回值参数 (来自增强类) --> <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/> </aop:aspect> </aop:config> </beans>