Spring 前置通知
前置通知顾名思意,该通知织入在方法调用之前。我们可以通过Spring 的MethodBeforeAdvice 接口实现。MethodBeforeAdvice 只提供方法before(),该方法无返回值,方法接受调用方法,方法参数和目标对象这3个参数。这里需要注意的是,虽然before()方法得到了调用方法的参数,这里值得注意的是方法参数可以进行更改!
例子如下:
1)前置通知代码:
public class Before implements MethodBeforeAdvice
{
public void before( Method method, Object[] args, Object target)throws Throwable {
System.out.println("Before.before()");
System.out.println("method name: " + method.getName());
Type[] type = method.getGenericParameterTypes();
for(int i = 0; i < type.length; i++) {
System.out.println(type[i].toString() + ": " + args[i]);
}
System.out.println("target: " + target.toString());
System.out.println("--------------------");
//对方法参数进行更改。
args[0] = new Integer(2);
for(int i = 0; i < type.length; i++) {
System.out.println(type[i].toString() + ": " + args[i]);
}
}
}
2)目标对象
public class Target implements Advice
{
public String test(int i, String s, float f) {
System.out.println("Target.test()");
System.out.println("target: " + this);
StringBuffer buf = new StringBuffer();
buf.append( "i = " + i);
buf.append( ", s = \"" + s + "\"");
buf.append( ", f = " + f);
return buf.toString();
}
}
3)接口定义
public interface Advice
{
String test(int i, String s, float f);
}
4)配置文件
<beans>
<bean id="before" class="spring.Before"/>
<bean id="aop" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces" value="spring.Advice" />
<property name="interceptorNames">
<list>
<value>before</value>
</list>
</property>
<property name="target">
<bean class="spring.Target" />
</property>
</bean>
</beans>