步骤:
1. 定义接口
2. 编写对象(被代理对象=目标对象)
3. 编写通知(前置通知目标方法调用前调用)
4. 在beans.xml文件配置
4.1 配置 被代理对象=目标对象
4.2 配置通知
4.3 配置代理对象 是 ProxyFactoryBean的对象实例
4.3.1
4.3.2 织入通知
4.3.3 配置被代理对象
本实例:
1、基本信息:
包名:com.aop
两个接口类:TestServiceInter.java;TestServiceInter2.java
测试类:Test1Service.java实现了上述两个接口
前置通知类:MyMethodBeforeAdvice.java
后置通知类:MyAfterReturningAdvice.java
环绕通知类:MyMethodInterceptor.java
异常通知类:MyThrowsAdvice.java
配置文件:beans.xml
应用操作类:App.java
2、接口类TestServiceInter.java中代码:
package com.aop;
public interface TestServiceInter {
public void sayHello();
}
3、接口类TestServiceInter2.java中代码:
package com.aop;
public interface TestServiceInter2 {
public void sayBye();
}
4、测试类Test1Service.java中代码:
package com.aop;
public class Test1Service implements TestServiceInter,TestServiceInter2 {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sayHello() {
System.out.println(“Hello!”+name);
}
public void sayBye() {
// TODO Auto-generated method stub
System.out.println(“Bye!”+name);
}
}
5、前置通知类MyMethodBeforeAdvice.java中代码:
package com.aop;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {
@Override//method:表示被调用的方法,args:给这个方法传递的参数;target:目标对象
public void before(Method method, Object[] args, Object target)
throws Throwable {
// TODO Auto-generated method stub
System.out.println(“***************************”);
System.out.println(“前置通知,记录日志…”+method.getName());
}
}
6、后置通知类MyAfterReturningAdvice.java中代码:
package com.aop;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class MyAfterReturningAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args,
Object target) throws Throwable {
// TODO Auto-generated method stub
System.out.println(“后置通知,关闭资源…”);
}
}
7、环绕通知类MyMethodInterceptor.java中的代码:
package com.aop;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MyMethodInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation arg0) throws Throwable {
// TODO Auto-generated method stub
System.out.println(“环绕通知,调用环绕方法前…”);
Object object=arg0.proceed();
System.out.println(“环绕通知,调用环绕方法后…”);
return null;
}
}
8、异常通知类MyThrowsAdvice.java中的代码:
在代码中设置一个异常即可检验出异常通知,例如int a=9/0异常;
package com.aop;
import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
public class MyThrowsAdvice implements ThrowsAdvice {
public void afterThrowing(Method m,Object[] os,Object target,Exception e) {
System.out.println(“出异常了…”+e.getMessage());
}
}
9、配置文件beans.xml中代码: