【spring】初识aop(面向切面编程) 使用jdk动态代理

BankServiceIImple.java

代码实现:

package com.zzxtit.aop;

import java.math.BigDecimal;

public interface BankServiceImple {
	public void transfer(String source, String target, BigDecimal money);
	
	public void withdraw(String account, BigDecimal money);
}

BankService.java

代码实现:

package com.zzxtit.aop;

import java.math.BigDecimal;

public class BankService implements BankServiceImple{

	public void transfer(String source, String target, BigDecimal money) {
		
	}

	public void withdraw(String account, BigDecimal money) {
		
	}

}

ServiceProxy.java

代码实现:

package com.zzxtit.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ServiceProxy implements InvocationHandler{
	
	private Object target;

	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		System.out.println("方法:" + method.getName() + "被执行");
		
		for(Object arg : args) {
			System.out.println("-参数" + arg);
		}
		
		Object returnValue = method.invoke(target,args);
		
		System.out.println("方法:" + method.getName() + "执行完毕,返回值:" + returnValue);
		
		return returnValue;
	}
	
	public Object createProxy(Object target) {
		this.target = target;
		
		return Proxy.newProxyInstance(this.target.getClass().getClassLoader(), this.target.getClass().getInterfaces(), this);
	}

}

注:

1、继承的接口是是jdk自带的,为固定写法

MaIn.java

代码实现:

package com.zzxtit.aop;

import java.math.BigDecimal;

public class Main {

	public static void main(String[] args) {
		
		BankServiceImple bs = new BankService();
		
		// JDK 动态代理
		
		BankServiceImple bsProxy = (BankServiceImple) new ServiceProxy().createProxy(bs);

		bsProxy.withdraw( "李四", new BigDecimal("500"));
	}
}

注:

1、该代码模拟了银行转账取钱的打印日志的操作,如果不使用面向切面编程则需要一个一个的添加打印日志的操作,如果方法很多则非常麻烦。

2、必须使用接口回调的方法

3、bs为被代理对象 bsProxy为代理对象,当调用被代理对象的方法时,会自动触发代理对象的invok方法

发布了128 篇原创文章 · 获赞 37 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/tyrant_forever/article/details/102927988
今日推荐