ProxyFactory 源码分析

介绍


spring 提供的编程式aop实现,即通过 ProxyFactory类完成的。

举例

@Test
public void testRemoveAdvisorByReference() {
    //被代理的对象
    TestBean target = new TestBean();
    //代理工厂
    ProxyFactory pf = new ProxyFactory(target);
    //拦截器1
    NopInterceptor nop = new NopInterceptor();
    //拦截器2
    CountingBeforeAdvice cba = new CountingBeforeAdvice();
    //增强点
    Advisor advisor = new DefaultPointcutAdvisor(cba);
    pf.addAdvice(nop);
    pf.addAdvisor(advisor);
    //获取代理对象
    ITestBean proxied = (ITestBean) pf.getProxy();
    //方法调用
    proxied.setAge(5);
    assertEquals(1, cba.getCalls());
    assertEquals(1, nop.getCount());
    assertTrue(pf.removeAdvisor(advisor));
    assertEquals(5, proxied.getAge());
    assertEquals(1, cba.getCalls());
    assertEquals(2, nop.getCount());
    assertFalse(pf.removeAdvisor(new DefaultPointcutAdvisor(null)));
}

ProxFactory源码分析


public class ProxyFactory extends ProxyCreatorSupport {
}

getProxy()方法分析

获取代理的对象

public Object getProxy() {
    return createAopProxy().getProxy();
}

createAopProxy()方法实现

protected final synchronized AopProxy createAopProxy() {
    //首次创建代理时进行激活。并调用相应的拦截器
    if (!this.active) {
        activate();
    }
    return getAopProxyFactory().createAopProxy(this);
}
/**创建代理*/
@Override
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
    if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
        Class<?> targetClass = config.getTargetClass();
        if (targetClass == null) {
            throw new AopConfigException("TargetSource cannot determine target class: " +
                    "Either an interface or a target is required for proxy creation.");
        }
        //如果被代理的类是一个接口。或者被代理的类的类型是Proxy类
        if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
            //使用jdk代理
            return new JdkDynamicAopProxy(config);
        }
        //否则使用cglib代理
        return new ObjenesisCglibAopProxy(config);
    }
    else {
        return new JdkDynamicAopProxy(config);
    }
}

具体看JdkDynamicAopProxy源码实现:
https://blog.csdn.net/ai_xiangjuan/article/details/79945536

Spring的ProxyFactory的方法——addInterceptor()

09-18

UserDao类:rnpackage com.sunyan.dao;rnrnimport java.util.HashMap;rnimport java.util.Map;rnimport java.util.Set;rnrnrnpublic class UserDao rn private Map map = new HashMap();rn public UserDao()rn map.put("admin", "security");rn map.put("test", "123");rn rn public void create(String username, String password)rn if(map.get(username)!=null)rn throw new RuntimeException("User exist");rn map.put(username, password);rn rn public void login(String username,String password)rn String pw = map.get(username);rn if(pw==null||!pw.equals(password))rn throw new RuntimeException("Login failed");rn rn public void print()rn System.out.println("User list:");rn Set keySet = (Set) map.keySet(); rn for(String key : keySet)rn System.out.println(key);rn rnrnrnUserService接口:rnpackage com.sunyan.service;rnrnpublic interface UserService rn void create(String username,String password);rn void login(String username,String password);rnrnUserServiceImpl类:rnpackage com.sunyan.service.impl;rnrnimport com.sunyan.dao.UserDao;rnimport com.sunyan.service.UserService;rnrnpublic class UserServiceImpl implements UserServicern private UserDao userDao;rn rn public void setUserDao(UserDao userDao) rn this.userDao = userDao;rn rnrn @Overridern public void create(String username, String password) rn userDao.create(username, password);rn rnrn @Overridern public void login(String username, String password) rn userDao.login(username, password);rn rn rnrnAopProxyFactory类:rnpackage com.sunyan.proxy;rnrnimport java.lang.reflect.InvocationHandler;rnimport java.lang.reflect.Method;rnimport java.lang.reflect.Proxy;rnrnimport org.springframework.aop.MethodBeforeAdvice;rnrnpublic class AopProxyFactory rn public static Object createProxy(final Object target,final MethodBeforeAdvice methodBeforeAdvice) rn return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(), new InvocationHandler() rn @Overridern public Object invoke(Object proxy, Method method,Object[] args) throws Throwable rn //首先调用切面的before方法rn methodBeforeAdvice.before(method, args, target);rn //然后调用实际对象的方法rn return method.invoke(target, args);rn rn );rn rnrn测试类:rnpackage com.sunyan.test;rnimport java.lang.reflect.Method;rnimport org.springframework.aop.MethodBeforeAdvice;rnimport org.springframework.aop.framework.ProxyFactory;rnimport com.sunyan.dao.UserDao;rnimport com.sunyan.proxy.AopProxyFactory;rnimport com.sunyan.service.UserService;rnimport com.sunyan.service.impl.UserServiceImpl;rnrnpublic class DynamicProxyTest rnrn rn public static void main(String[] args) rn UserDao userDao = new UserDao();rn UserServiceImpl target = new UserServiceImpl();rn target.setUserDao(userDao);rn rn //创建日志记录切面rn MethodBeforeAdvice log = new MethodBeforeAdvice()rn @Overridern public void before(Method m, Object[] args, Object target)rn throws Throwable rn System.out.println("call method: "+ m.getName());rn rn ;rn rn /*//创建代理类rn UserService userService = (UserService) AopProxyFactory.createProxy(target, log);rn rn //调用代理类的方法rn userService.create("aop", "password");rn userService.login("aop", "password");rn rn userDao.print();*/rn rn //我想使用的是Spring的ProxyFactory类,可是addInterceptor方法报错,说没有此方法。rn ProxyFactory factory = new ProxyFactory(target);rn factory.addInterceptor(log);rn UserService userService = (UserService) factory.getProxy();rn userService.create("aop", "password");rn userService.login("aop", "password");rn rn userDao.print();rn rnrnrn在测试类中的:factory.addInterceptor(log);出错,报说没有此方法,为什么?

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试

关闭