public interface CheckInterface {
public abstract void check(String name);
public abstract void excute(String name);
}
再做一個基類:
public abstract class BaseClass implements CheckInterface {
public BaseClass() {
}
public void check(String name){
if (name.equals("supervisor"))
System.out.else {
System.out.println("No access privilege! Please do sth. else!");
}
}
}
再做一個測試類:
public class ExcuteClass extends BaseClass {
public ExcuteClass() {
}
public void excute(String name){
System.out.println("Excute here!"+name);
}
}
好了,下面做一個通知類(Advice):
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
import org.apache.log4j.Logger;
public class BeforeAdvisor implements MethodBeforeAdvice {
private static Logger logger=Logger.getLogger(BeforeAdvisor.class);
public void before(Method m, Object[] args, Object target) throws Throwable {
if (target instanceof CheckInterface){
logger.debug("Is Instanceof CheckInterface!!!");
CheckInterface ci=(CheckInterface)target;
ci.check((String)args[0]);
}
}
}
其中重要的before方法的參數(shù):Object target傳入的通知的對象(即測試類的接口),Method m, Object[] args分別是該對象被調(diào)用的方法和參數(shù)。我們再來作spring bean定義xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<description>Spring Quick Start</description>
<bean id="MyAdvisor" class="com.wysm.netstar.test.springaop.BeforeAdvisor"/>
<bean id="myPointcutAdvisor2" class="org.springframework.aop.support.RegeXPMethodPointcutAdvisor">
<property name="advice">
<ref local="MyAdvisor" />
</property>
<property name="patterns">
<list>
<value>.*excute.*</value>
</list>
</property>
</bean>
<bean id="checkInterface" class="com.wysm.netstar.test.springaop.ExcuteClass"/>
<bean id="myCheckClass" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>com.wysm.netstar.test.springaop.CheckInterface</value>
</property>
<property name="target">
<ref local="checkInterface" />
</property>
<property name="interceptorNames">
<value>myPointcutAdvisor2</value>
</property>
</bean>
</beans>
這個定義文件指明了ExcuteClass為監(jiān)視對象,它的excute方法被執(zhí)行的時候,BeforeAdvisor將被調(diào)用。
新聞熱點
疑難解答