Spring AOP(Annotation)的原理模拟实现
模拟需要织入的行为:记录日志
package com.spring;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
//需要实现InvocationHandler接口
public class LogInterceptor implements InvocationHandler {
??? //被代理对象
?private Object target;
???
??? public void beforeMethod(Method m) {
??? ?System.out.println(m.getName()+" start logger!!!!!");
??? }
?public Object invoke(Object proxy, Method method, Object[] args)
???throws Throwable {
??this.beforeMethod(method);
??method.invoke(target, args);
??return null;
?}
?public Object getTarget() {
??return target;
?}
?public void setTarget(Object target) {
??this.target = target;
?}
}
测试类:
package com.test;
import java.lang.reflect.Proxy;
import com.dao.UserDao;
import com.dao.UserDaoImpl;
import com.model.User;
import com.spring.LogInterceptor;
public class InterceptorTest {
?public static void main(String[] args) {
???? UserDao userDao = new UserDaoImpl();
???? LogInterceptor log = new LogInterceptor();
???? log.setTarget(userDao);//设置被代理对象
? //创建UserDao的代理对象
??? UserDao userDaoProxy = (UserDao)Proxy.newProxyInstance(UserDao.class.getClassLoader(), new Class[]{UserDao.class}, log);
?? System.out.println(userDaoProxy.getClass());//userDaoProxy是一个UserDao的代理对象
??? userDaoProxy.save(new User());
??? userDaoProxy.delete(new User());
?}
}
?