一个简单的AOP实例,仅供参考;
package com.aop.service; public interface Service { String addUser() throws Exception; }
此类为目标对象接口类
package com.aop.service.impl; import com.aop.service.Service; public class ServiceImpl implements Service { public String addUser() throws Exception { System.out.println("您好,业务方法 ServiceImpl 开始执行");
//下面这句在于演示异常通知的效果,如去掉,便可以看到后置通知的结果,试试看 throw new Exception(); } }
此类为目标对象接口实现类
package com.aop.service; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; public class BeforeAdvice implements MethodBeforeAdvice{ public void before(Method method,Object[] args,Object target) throws Throwable{ System.out.println("前置通知:"+target.getClass().getName()+"的"+method.getName()+"方法将运行"); } }
前置通知:即在目标对象实现类方法执行之前执行的方法类
package com.aop.service; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class AfterAdvice implements AfterReturningAdvice{ public void afterReturning(Object returnValue,Method method,Object[] args,Object target) throws Throwable{ System.out.println("后置通知:"+target.getClass().getName()+"的"+method.getName()+" 方法返回结果:"+ returnValue); } }
后置通知:即在目标对象实现类方法执行之后执行的方法类
package com.aop.service; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class RoundAdvice implements MethodInterceptor { public Object invoke(MethodInvocation arg0) throws Throwable{
System.out.println("环绕通知:"); System.out.println("target is: class="+arg0.getThis().getClass().getName()+",method="+arg0.getMethod().getName()); System.out.println("---begin to call target's method..."); Object obj=arg0.proceed(); System.out.println("---finished from target's method"); return obj; } }
环绕通知:即在目标对象实现类方法执行当中执行的方法类
package com.aop.service ; import org.omg.CORBA.UserException; import org.springframework.aop.ThrowsAdvice; public class ThrowAdvice implements ThrowsAdvice{ //public void afterThrowing(UserNameDuplicateException ex){ public void afterThrowing(Exception ex){ System.out.println("异常通知:"+ex.getMessage()); } }
异常通知:即在目标对象实现类中报异常时执行的方法类
package com.aop.service; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; public class AOPStart { public static void main(String []arg) throws Exception { ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml"); Service s = (Service)ctx.getBean("service"); s.addUser(); } }
测试类AOPStart