设计AOP 基础实现-AfterThrowingAdviceInterceptor

public class V1AfterThrowingAdviceInterceptor extends V1AbstractAspectAdvice implements V1Advice,V1MethodInterceptor {


    private String throwingName;

    public V1AfterThrowingAdviceInterceptor(Method aspectMethod, Object aspectTarget) {
        super(aspectMethod, aspectTarget);
    }

    @Override
    public Object invoke(V1MethodInvocation mi) throws Throwable {
        try {
            return mi.proceed();
        }catch (Throwable e){
            invokeAdviceMethod(mi,null,e.getCause());
            throw e;
        }
    }

    public void setThrowName(String throwName){
        this.throwingName = throwName;
    }
}

接入getBean()方法找到V1ApplicationContext 的getBean()方法,我们知道getBean()中负责Bean 初始化的方法其实就是instantiateBean(),我们在初始化时就可以确定是否返回原生Bean 还是Proxy Bean。代码实现如下:

private Object instantiateBean(String beanName, V1BeanDefinition V1BeanDefinition) {
	//1、拿到要实例化的对象的类名
	String className = V1BeanDefinition.getBeanClassName();

	//2、反射实例化,得到一个对象
	Object instance = null;
	try {
//            V1BeanDefinition.getFactoryBeanName()
		//假设默认就是单例,细节暂且不考虑,先把主线拉通
		if(this.factoryBeanObjectCache.containsKey(className)){
			instance = this.factoryBeanObjectCache.get(className);
		}else {
			Class<?> clazz = Class.forName(className);
			instance = clazz.newInstance();

			V1AdvisedSupport config = instantionAopConfig(V1BeanDefinition);
			config.setTargetClass(clazz);
			config.setTarget(instance);

			//符合PointCut的规则的话,闯将代理对象
			if(config.pointCutMatch()) {
				instance = createProxy(config).getProxy();
			}

			this.factoryBeanObjectCache.put(className,instance);
			this.factoryBeanObjectCache.put(V1BeanDefinition.getFactoryBeanName(),instance);
		}
	}catch (Exception e){
		e.printStackTrace();
	}

	return instance;
}
private V1AdvisedSupport instantionAopConfig(V1BeanDefinition V1BeanDefinition) {
	V1AopConfig config = new V1AopConfig();
	config.setPointCut(this.reader.getConfig().getProperty("pointCut"));
	config.setAspectClass(this.reader.getConfig().getProperty("aspectClass"));
	config.setAspectBefore(this.reader.getConfig().getProperty("aspectBefore"));
	config.setAspectAfter(this.reader.getConfig().getProperty("aspectAfter"));
	config.setAspectAfterThrow(this.reader.getConfig().getProperty("aspectAfterThrow"));
	config.setAspectAfterThrowingName(this.reader.getConfig().getProperty("aspectAfterThrowingName"));
	return new V1AdvisedSupport(config);
}
private V1AopProxy createProxy(V1AdvisedSupport config) {

	Class targetClass = config.getTargetClass();
	if(targetClass.getInterfaces().length > 0){
		return new V1JdkDynamicAopProxy(config);
	}
	return new V1CglibAopProxy(config);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值