接口和实现类见LogBeforeAdvice的例子
package net.blogjava.dodoma.spring.aop;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AfterReturningAdvice;
public class LogAfterAdvice implements AfterReturningAdvice {
protected static final Log log = LogFactory.getLog(LogAfterAdvice.class);
public void afterReturning(Object returnVal, Method m, Object[] args,
Object target) throws Throwable {
// TODO Auto-generated method stub
log.info("in the class "+this.getClass().getName()+"'s method afterReturning()");
log.info("the target class is:" + target.getClass().getName());
log.info("the target method is:" + m.getName());
for (int i = 0; i < args.length; i++) {
log.info("the method's args is:" + args[i]);
}
log.info("the returnValue is "+returnVal);
//测试,如果返回装备发生了异常.将如何处理程序流程
//throw new Exception("返回装备发生异常");
}
}
测试代码
package net.blogjava.dodoma.spring.aop;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class HelloTest {
protected static final Log log = LogFactory.getLog(HelloTest.class);
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Resource rs = new ClassPathResource("beans.xml");
BeanFactory bf = new XmlBeanFactory(rs);
HelloI h = (HelloI) bf.getBean("theBean");
log.info("starting...");
try {
log.info(h.sayHello("ma", "bin"));
} catch (Exception e) {
e.printStackTrace();
}
log.info("end...");
ProxyFactory factory=new ProxyFactory();
factory.addAdvice(new LogAfterAdvice());
factory.setTarget(new Hello("hello"));
try{
HelloI hi=(HelloI)factory.getProxy();
hi.sayHello("ma","bin");}
catch(Exception e){e.printStackTrace();}
}
}
在beans.xml中加入如下代码
<bean id="theLogAfterAdvice" class="net.blogjava.dodoma.spring.aop.LogAfterAdvice"/>
<property name="interceptorNames">
<list>
<value>theLogAfterAdvice</value><!--此时直接使用advice,表明这个类所有的实例,方法,都享受advice的拦截-->
</list>
</property>
切入点可省略,如需要的话
如
<!--切入点-->
<!--Note: An advisor assembles pointcut and advice-->
<bean id="theBeAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="theLogAfterAdvice"/>
</property>
<!--匹配模式-->
<property name="pattern">
<value>.*</value>
</property>
</bean>
posted on 2006-03-28 12:37
dodoma 阅读(404)
评论(0) 编辑 收藏 所属分类:
spring