Spring原理自我实践之AOP的实现原理
2009-09-18 00:00:00 来源:WEB开发网模拟客户端:
Java代码
package com.erong.spring.aop.myaop;
import java.util.*;
/**
* 模拟底层DAO
*
* @author citizen
*
*/
public class UserDao {
private Map<String, String> map = new HashMap<String, String>();
public UserDao() {
map.put("admin", "security");
map.put("test", "123456");
}
public Map<String, String> getUserMap() {
System.out.println("用户名列表:");
Set<String> keySet = map.keySet();
for (String key : keySet) {
System.out.println(key + " " + map.get(key));
}
return this.map;
}
/**
* 模拟创建用户
*
* @param username
* @param password
*/
public void create(String username, String password) {
if (map.get(username) != null)
throw new RuntimeException("添加失败,用户已存在User exist!");
map.put(username, password);
}
/**
* 模拟登录
*
* @param username
* @param password
*/
public void login(String username, String password) {
String pw = map.get(username);
if (pw == null || !pw.equals(password))
throw new RuntimeException("登录失败 Login failed.");
}
/**
* 打印出目前已有的用户信息
*/
public void print() {
System.out.println("用户名列表:");
Set<String> keySet = map.keySet();
for (String key : keySet) {
System.out.println(key + " " + map.get(key));
}
}
}
AOP的代理工厂:
Java代码
package com.erong.spring.aop.myaop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import org.springframework.aop.MethodBeforeAdvice;
/**AOP代理工厂
* @author citizen
*
*/
public class AopProxyFactory {
/**创建代理
* @param target
* @param methodBeforeAdvice
* @return
*/
public static Object createProxy(final Object target, final MethodBeforeAdvice methodBeforeAdvice) {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {//匿名内部类
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
methodBeforeAdvice.before(method, args, target);
return method.invoke(target, args);
}
});
}
更多精彩
赞助商链接