和前文一樣,aop示例也拿helloworld演示。
IHelloService 接口:
public interface IHelloService {public void sayHello();}
HelloServiceImpl 實現類
public class HelloServiceImpl implements IHelloService{@Overridepublic void sayHello(){System.out.println("Hello!");}}
IHelloAction 接口
public interface IHelloAction {/** 方便JUnit測試,增加返回值*/public boolean sayHello();}
HelloActionImpl 實現類
public class HelloActionImpl implements IHelloAction{private IHelloService helloService;public boolean sayHello(){/** 增加try-catch用于JUnit測試*/boolean flag = true;try {helloService.sayHello();} catch (RuntimeException e) {e.printStackTrace();flag = false ;}return flag;}
public void setHelloService(IHelloService helloService) {this.helloService = helloService;}
}
spring配置:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans<bean id="helloService" class="cn.com.ultrapower.service.HelloServiceImpl"></bean><bean id="helloActionTarget" class="cn.com.ultrapower.action.HelloActionImpl"><property name="helloService"><ref bean="helloService"/></property></bean><!--設置一個日志監聽器--><bean id="logAdvisorBefore" class="cn.com.ultrapower.advice.ordinary.LogAdvisorBefore" /><!--利用aop實現日志監聽支持--><bean id="helloAction" class="org.springframework.aop.framework.ProxyFactoryBean"><property name="proxyInterfaces"><value>cn.com.ultrapower.action.IHelloAction</value></property><!--被代理對象--><property name="target"><ref local="helloActionTarget"/></property><!--攔截器--><property name="interceptorNames"><list><value>logAdvisorBefore</value></list></property></bean></beans>
logAdvisorBefore 是用于在方法執行前監聽,helloAction并不直接指向HelloActionImpl類,而是通過ProxyFactoryBean創建。helloActiond的target屬性引用了helloActionTarget bean,并且增加了proxyInterfaces和interceptorNames兩個屬性。前者指向IHelloAction接口,后者是一list,也就意味著可以增加多個攔截器。如果使用過spring的事務,對上面代碼的方式應該很熟悉。
logAdvisorBefore 代碼如下:
public class LogAdvisorBefore implements MethodBeforeAdvice {/*** method - method being invoked* args - arguments to the method* target - target of the method invocation. May be null.*/@Overridepublic void before(Method method, Object[] args, Object target)throws Throwable {System.out.println("Log:do something before call");System.out.println("Log:call method name:"+method.getName());}
從實現的是MethodBeforeAdvice 接口的字面意思上就可以看出,這個是一個在方法執行前的監聽器(這里是用監聽不使用攔截是因為攔截有阻止執行的功能,而MethodBeforeAdvice 沒有這個功能)
使用junit測試上面代碼,輸出如下:
Log:do something before call
Log:call method name:sayHello
Hello!
posted on 2008-06-07 15:12 flyoo 閱讀(79) 評論(0) 編輯 收藏
Powered by: BlogJava Copyright © flyoo