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);
}