首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

spring的通报(advice)

2012-10-28 
spring的通知(advice)spring的通知(advice)分为方法通知和异常通知;方法通知又有方法调用前(MethodBeforeA

spring的通知(advice)

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 stubSystem.out.println("before");}//方法后通知public void afterReturning(Object arg0, Method arg1, Object[] arg2,Object arg3) throws Throwable {// TODO Auto-generated method stubSystem.out.println("after");}//方法调用过程中public Object invoke(MethodInvocation arg0) throws Throwable {// TODO Auto-generated method stubSystem.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" ref="userDao"></property></bean><!-- 定义通知 --><bean id="userAdvice" ><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 stubApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");UserService service = (UserService) context.getBean("userService");service.list();service.login("ligson", "admin");service.login("ligson", null);}}

?解释:

在userDao中定义用户登录,如果用户名或密码为空则抛出空指针异常;而这个异常必须以异常通知中的 afterThrowing方法参数异常一致;

?

热点排行