sprig AOP之ProxyFactory

我们在项目中大多使用的声明式的AOP配置,其实在spring中也提供了编程式的AOP实现方法,具体在ProxyFactory中例如ProxyFactory例子如下:

TargetImpl target = new TargetImpl();

ProxyFactory proxy = new ProxyFactory ();

target.addAdvisor(youAdvisor);

target.addAdvice(youAdvice);

TargetImpl targetproxy = proxy.getProxy();

proxyFactory类的源码如下:
public class ProxyFactory extends ProxyCreatorSupport
{

public ProxyFactory()
{
}

public ProxyFactory(Object target)
{
Assert.notNull(target, "Target object must not be null");
setInterfaces(ClassUtils.getAllInterfaces(target));
setTarget(target);
}

public ProxyFactory(Class proxyInterfaces[])
{
setInterfaces(proxyInterfaces);
}

public ProxyFactory(Class proxyInterface, Interceptor interceptor)
{
addInterface(proxyInterface);
addAdvice(interceptor);
}

public ProxyFactory(Class proxyInterface, TargetSource targetSource)
{
addInterface(proxyInterface);
setTargetSource(targetSource);
}

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

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

public static Object getProxy(Class proxyInterface, Interceptor interceptor)
{
return (new ProxyFactory(proxyInterface, interceptor)).getProxy();
}

public static Object getProxy(Class proxyInterface, TargetSource targetSource)
{
return (new ProxyFactory(proxyInterface, targetSource)).getProxy();
}

public static Object getProxy(TargetSource targetSource)
{
if(targetSource.getTargetClass() == null)
{
throw new IllegalArgumentException("Cannot create class proxy for TargetSource with null target class");
} else
{
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.setTargetSource(targetSource);
proxyFactory.setProxyTargetClass(true);
return proxyFactory.getProxy();
}
}
}
proxyFactory的实现原理与ProxyFactoryBean的实现原理是一样的,只是在最外层的表示形式有所不同,proxyFactory没有使用proxyFactoryBean的IoC封装,而是通过直接继承ProxyCreatorSupport的功能来完成AOP的属性配置。

具体实例
/**
* 具体的拦截器类
*/
public class TestInterceptor implements MethodInterceptor
{
@Override
public Object invoke(MethodInvocation invocation) throws Throwable
{
System.out.print("zhangsan start.....");
Object retVal = invocation.proceed();
System.out.print("end");
return retVal;
}

}

//具体业务类
public class Loginservice
{
public void login()
{
System.out.println("this is login method");
}
}

//测试类
public class Test
{
public static void main(String[] args)
{
//具体的业务逻辑
Loginservice loginservice = new Loginservice();
//代理工厂
ProxyFactory pf = new ProxyFactory(loginservice);
//添加advice
pf.addAdvice(new TestInterceptor());
//产生代理对象
Loginservice lg = (Loginservice) pf.getProxy();
lg.login();
}
}

这只是简单的通过编码完成了spring的AOP功能。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值