Spring AOP使用配置介绍(五):基于Schema配置的aop
如果项目中不能使用JDK5.0,那就无法使用基于@AspectJ注解的切面。但是我们仍可以使用AspectJ切点表达式,可以用Schema配置的方法来代替。
首先定义一个增强:
package com.maxjay.bank.advice.schema;import org.apache.log4j.Logger;import org.aspectj.lang.JoinPoint;import com.maxjay.bank.model.TSysUser;public class LoggerAdvice {private Logger logger = Logger.getLogger(LoggerAdvice.class);/** * JoinPoint为连接点的信息,可以通过jp获取到代理类的类型、要执行的方法及其参数 * @param jp */public void preLogger(JoinPoint jp) {logger.info("前置增强,使用schema方法配置");StringBuffer sb = new StringBuffer();for(Object s:jp.getArgs()){sb.append(s.toString()+",");}logger.info("代理对象执行的方法名为:" + jp.getSignature().getName() + ",方法参数为:"+ sb.toString());}/** * JoinPoint为连接点的信息,可以通过jp获取到代理类的类型、要执行的方法及其参数 * @param jp * @param user 代理方法的返回值 */public void postLogger(JoinPoint jp, TSysUser user) {logger.info("后置增强,代理对象执行的结果返回值为:" + user.getUserName());}}
<?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:tx="http://www.springframework.org/schema/tx" xmlns:lang="http://www.springframework.org/schema/lang"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> 此段头部声明必须添加,尤其是aop的声明部分,否则下面的配置无法使用 .........<!-- 使用schema方式配置aop --><!-- 将要使用的增强类定义成bean --><bean id="loggerAdvice" /><aop:config proxy-target-/><aop:after-returning method="postLogger"pointcut="target(com.maxjay.bank.service.impl.TestAdviceService) and execution(* validateUser(..))" returning="user"/></aop:aspect></aop:config>
<!-- 使用文章(一)中用接口方法定义的增强 --><bean id="loggerBeforeAdvice" /><aop:config proxy-target-/></aop:config>