使用BeanNameAutoProxyCreator配置自动代理时如果某个bean没有实现任何接口,比如
public classMyBean
{
}
则会报错java.lang.ClassNotFoundException:org.objectweb.asm.Type
当然引入cglib.jar和asm.jar是没有问题的,需要注意版本问题(我使用的cglib-2.2.2和asm-3.3.1)如果cglib和asm两个jar包版本不是匹配的有可能出现错误。
下面要讨论的是不实现任何接口的bean为什么要使用asm包,而实现了某些接口则可以不适用asm包。
DefaultAopProxyFactory.class
publicAopProxy createAopProxy(AdvisedSupport config) throws AopConfigException{
if(config.isOptimize() || config.isProxyTargetClass() ||hasNoUserSuppliedProxyInterfaces(config)) {
//需要优化或者直接代理的类而不是接口或者用户没有提供接口或者用户提供了一个接口是SpringProxy
ClasstargetClass = config.getTargetClass();
if(targetClass == null) {
thrownew AopConfigException("TargetSource cannot determine target class:" +
"Eitheran interface or a target is required for proxy creation.");
}
if(targetClass.isInterface()) {
//targetClass是个接口的情况还没想到如何通过配置文件配置出来,因为bean不可能是接口类型,所以这个应该只是提供给代码修改targetClass的时候做的判断吧
returnnew JdkDynamicAopProxy(config);
}
if(!cglibAvailable) {
throw new AopConfigException(
"Cannotproxy target class because CGLIB2 is not available. " +
"AddCGLIB to the class path or specify proxy interfaces.");
}
return CglibProxyFactory.createCglibProxy(config);
}
else{
return new JdkDynamicAopProxy(config);
}
}
很容易可以看出如果
1.给自动代理配置了Optimize为true
2.或者配置了ProxyTargetClass为true
3.或者没有给待代理类提供接口
4.或者提供的接口为SpringProxy
则会使用cglib的代理工厂;
如果使用到cglib的代理工厂创建proxy(Cglib2AopProxy),
Cglib2AopProxy会使用到Enhancer类,
而该类有使用 private static finalorg.objectweb.asm.Type FACTORY; 所以会缺少asm包。