接口和實現類見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 閱讀(409)
評論(0) 編輯 收藏 所屬分類:
spring