AOP代理即面向切面的思想里加入了动态代理技术,使用AOP代理我们可以在不改动原有业务类的基础下新增一些业务进去。实现思路如下图所示:
下面是一个简单例子的代码:
1、Dog接口
- public interface Dog {
- public void info();
- public void run();
- }
2、GunDog实现类
- public class GunDog implements Dog {
- @Override
- public void info() {
- System.out.println("It's a dog");
- }
- @Override
- public void run() {
- System.out.println("This dog run quickly");
- }
- }
3、DogUtil类,新增加的处理方法
- public class DogUtil {
- public void method1(){
- System.out.println("=========this is the first method==========");
- }
- public void method2(){
- System.out.println("=========this is the second method=========");
- }
- }
4、MyInvocationHandler类需要实现InvocationHandler抽象接口
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- public class MyInvocationHandler implements InvocationHandler {
- //需要被代理的对象
- private Object target;
- public void setTarget(Object target){
- this.target = target;
- }
- //执行动态代理的所有方法时,都会被替换成如下的invoke方法
- @Override
- public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
- DogUtil du = new DogUtil();
- //执行method1方法
- du.method1();
- //以target作为主调来执行method方法
- Object result = method.invoke(target, args);
- //然后在执行method2方法
- du.method2();
- return result;
- }
- }
5、工厂MyProxyFactory类,通过反射机制获取动态代理
- import java.lang.reflect.Proxy;
- public class MyProxyFactory {
- //为指定target对象生成动态代理
- public static Object getProxy(Object target) throws Exception{
- //创建一个MyInvocationHandler对象
- MyInvocationHandler handler = new MyInvocationHandler();
- //为MyInvocationHandler设置target对象
- handler.setTarget(target);
- //创建并返回一个动态代理
- return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
- }
- }
6、测试TestAop类
- public class TestAop {
- /**
- * @param args
- */
- public static void main(String[] args) throws Exception{
- //创建一个原始GunDog对象作为target
- Dog target = new GunDog();
- //以指定的target来创建动态代理
- Dog dog = (Dog) MyProxyFactory.getProxy(target);
- dog.info();
- dog.run();
- }
- }