spring的通知(advice)分为方法通知和异常通知;方法通知又有方法调用前(MethodBeforeAdvice),调用中(MethodInterceptor),调用后(AfterReturningAdvice)三种,这三种实现其接口即可;但异常通知在实现ThrowsAdvice后还需手动加入代码,这一点我就不知道为什吗了,哪位高手可以解释一下;下面是我的实现代码;
通知代码:
package login.aop;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;
public class AdviceTest implements MethodBeforeAdvice,AfterReturningAdvice,MethodInterceptor,ThrowsAdvice {
//方法前通知
public void before(Method arg0, Object[] arg1, Object arg2)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("before");
}
//方法后通知
public void afterReturning(Object arg0, Method arg1, Object[] arg2,
Object arg3) throws Throwable {
// TODO Auto-generated method stub
System.out.println("after");
}
//方法调用过程中
public Object invoke(MethodInvocation arg0) throws Throwable {
// TODO Auto-generated method stub
System.out.println(arg0.getMethod().getName()+" invoking.....");
return arg0.proceed();
}
//异常通知
public void afterThrowing(NullPointerException exception){
System.out.println("exception.....");
}
public void afterThrowing(Method method,Object[] objects,Object target,Throwable throwable){
}
}
beans.xml文件配置:
<!-- 定义目标对象 --> <bean id="userServiceTarget" class="login.service.impl.UserServiceImpl"> <property name="dao" ref="userDao"></property> </bean> <!-- 定义通知 --> <bean id="userAdvice" class="login.aop.AdviceTest"> </bean> <!-- 定义代理对象,这里用的spring的代理工厂bean--> <bean id="userService" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="targetName" > <value>userServiceTarget</value> </property> <property name="proxyInterfaces"> <value>login.service.UserService</value> </property> <property name="interceptorNames"> <list> <value>userAdvice</value> </list> </property> </bean>
测试代码:
package login.test;
import login.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyAdvice {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService service = (UserService) context.getBean("userService");
service.list();
service.login("ligson", "admin");
service.login("ligson", null);
}
}
解释:
在userDao中定义用户登录,如果用户名或密码为空则抛出空指针异常;而这个异常必须以异常通知中的 afterThrowing方法参数异常一致;