全部博文(155)
分类: Java
2011-09-25 16:31:59
http://joe5456536.blog.163.com/blog/static/8537477320112119372998/
ApplicationContext.xml 文件
"">
myBeforeAdvice" />
myAroundAdvice" />
myThrowsAdvice" />
myAfterAdvice" />
Spring 里的通知类
前置通知:
package com.demo.spring.aop;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MyBeforeAdvice implements MethodBeforeAdvice {
public void before(Method arg0, Object[] args, Object target) throws Throwable {
System.out.println("方法名:" + arg0.getName());
System.out.println("参数个数:" + arg1.length);
System.out.println("目标类名:" + target);
System.out.println("Start to say:");
}
}
环绕通知:
package com.demo.spring.aop;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MyAroundAdvice implements MethodInterceptor {
public Object invoke(MethodInvocation arg0) throws Throwable {
System.out.println("正在执行!");
System.out.println("代理类名:" + arg0.getClass().getName());
System.out.println("目标类名:" + arg0.getThis().getClass().getName());
System.out.println("参数个数:" + arg0.getArguments().length);
System.out.println("目标方法名:" + arg0.getMethod());
return arg0.proceed();
}
}
返回后通知:
package com.demo.spring.aop;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class MyAfterAdvice implements AfterReturningAdvice {
public void afterReturning(Object returnVal, Method arg1, Object[] args, Object target) throws Throwable {
System.out.println("END!");
}
}
异常通知:
package com.demo.spring.aop;
import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
public class MyThrowsAdvice implements ThrowsAdvice {
public void afterThrowing(Method m, Object[] args, Object target, Exception ex) throws Throwable{
System.out.println("有异常抛出!");
}
}
接口类:
package com.demo.spring.test;
public interface IHelloWorld {
public void execute(String name) throws Exception;
}
接口实现类:
package com.demo.spring.test;
import java.io.IOException;
public class HelloWorld implements IHelloWorld {
public void execute(String name) throws Exception{
System.out.println("Hello World!");
//if(true) throw new IOException();
}
}
测试类:
package com.demo.spring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx = new FileSystemXmlApplicationContext("/applicationContext.xml");
IHelloWorld hello = (IHelloWorld) ctx.getBean("proxy");
try{
hello.execute("JOE");
}catch(Exception e){
e.printStackTrace();
}
}
}