我在运行时将额外的单例 bean 定义从外部 jar 文件加载到我的应用程序的现有 XmlWebApplicationContext 中:
BeanFactory beanFactory = xmlWebApplicationContext.getBeanFactory();
DefaultListableBeanFactory defaultFactory = (DefaultListableBeanFactory)beanFactory;
final URL url = new URL("external.jar");
final URL[] urls = {url};
ClassLoader loader = new URLClassLoader(urls, this.getClass().getClassLoader());
defaultFactory.setBeanClassLoader(loader);
final ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(defaultFactory);
final DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
resourceLoader.setClassLoader(loader);
scanner.setResourceLoader(resourceLoader);
scanner.scan("com.*");
Object bean = xmlWebApplicationContext.getBean("externalBean");
毕竟上面的 xmlWebApplicationContext 包含 bean 的所有外部定义。但是当我试图从上下文中获取bean时抛出异常:
Couldn't generate CGLIB proxy for class ...
我在调试模式下看到,在 bean 初始化过程中,第一次代理是由
org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator
然后尝试生成代理
org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator
但因提到的异常而失败。