---
title: "一个常见的Spring IOC疑难症状"
author: "stamen"
date: "2013-07-25T14:14:26Z"
tags: ["Spring"]
categories: ["开源软件"]
slug: "spring-ioc"
draft: false
lastmod: "2013-07-25T14:34:37Z"
id: 1913341
url: "https://stamen.iteye.com/blog/1913341"
---

\[b]\[size=x-large]Case\[/size]\[/b] 请看下面的IOC实例： 1）AaaService实现AaaaInterface接口 2）在BaaService中Autowired AaaService \[b]\[size=large]Code\[/size]\[/b] \[code="java"] //1.AaaInterface package com.test; public interface AaaInterface { void method1(); } //2.AaaService package com.test; public class AaaService implements AaaInterface { @Override public void method1() { System.out.println("hello"); } public void method2() { System.out.println("hello"); } } //3.BbbService package com.test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; public class BbbService { @Autowired private AaaService aaaService; public void method2(){ System.out.println("hello method2"); } } \[/code] \[b]\[size=large]Spring XML配置\[/size]\[/b] \[code="xml"] \[/code] \[b]\[size=large]启动Spring容器\[/size]\[/b] \[code="java"] package com.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainStarter { public static void main(String\[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); BbbService bbbService = applicationContext.getBean("bbbService", BbbService.class); } } \[/code] 结果报了以下这堆异常： \[code="java"] 2013-7-25 13:54:08 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons 信息: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@687bc899: defining beans \[org.springframework.context.support.PropertySourcesPlaceholderConfigurer#0,aaaService,bbbService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,dataSource,txManager,org.springframework.aop.config.internalAutoProxyCreator,serviceMethod,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0,txAdvice,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy //重要的信息在这儿！！ Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bbbService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.test.AaaService com.test.BbbService.aaaService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type \[com.test.AaaService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288) at ... 50 more \[/code] 上面的异常告诉我们，BbbService Bean创建不了，因为无法Autowired其aaaService的成员变量，说在Spring容器中不存在这个AaaService的Bean. \[b]\[size=x-large]分析\[/size]\[/b] 以上是Spring IoC中一个经典的错误，其原因是Spring对Bean的动态代理引起的： 1)由于在applicationContext.xml中，通过对所有Service进行事务增强，因此Spring容器会对所有所有XxxService的Bean进行动态代理； 2)默认情况下，Spring使用基于接口的代理，也即： a)如果Bean类有实现接口，那么Spring自动使用基于接口的代理创建该Bean的代理实例； b)如果Bean类没有实现接口，那么则使用基于子类扩展的动态代理（即CGLib代理）； 3）由于我们的AaaService实现了AaaInterface，所以Spring在生成AaaService类的动态代理Bean时，采用了 基于接口的动态代理，该动态代理实例只实现AaaInterface，且该实例不能强制转换成AaaService。\[color=red]换句话说，AaaService生成的Bean不能赋给AaaService的实例，而只能赋给AaaInterface的实例。\[/color] 4)因此，当BbbService希望注入AaaService的成员时，Spring找不到对应的Bean了（因为只有AaaInterface的Bean）. \[b]\[size=x-large]解决\[/size]\[/b] \[b]\[size=large]方法1\[/size]\[/b] 既然AaaService Bean是被Spring动态代理后改变成了类型，那如果取消引起动态代理的配置，使Spring不会对AaaService动态代理，那么AaaService的Bean类型就是原始的AaaService了： \[code="xml"] ... \[/code] 引起Spring对AaaService进行动态代理的配置注释后，重新启动容器，即可正常启动了。 但是这里AaaService的方法就不会被事务增强了，这将违背了我们的初衷，因此这种解决方法仅是为了让大家了解到引起IOC问题的根源所在，并没有真正解决问题。 \[b]\[size=large]方法2\[/size]\[/b] 将BbbService的AaaService成员改成AaaInterface： \[code="java"] @Service("bbbService") public class BbbService { @Autowired private AaaInterface aaaService;//注意这儿，成员类型从AaaService更改为AaaInterface public void method2(){ System.out.println("hello method2"); } } \[/code] 既然AaaService Bean被植入事务增强动态代理后就变成了AaaInterface的实例，那么干脆我们更改BbbService的成员属性类型，也是可以解决问题的。 但是这样的话，只能调用接口中拥有的方法 ，在AaaService中定义的方法（如method2())就调用不到了，因为这个代理后的Bean不能被强制转换成AaaService。 因此，就引出了我们的终极解决办法，请看方法3： \[b]\[size=large]方法3\[/size]\[/b] 刚才我们说\[color=red]\[b]“Spring在默认情况下，对实现接口的Bean采用基于接口的代理”\[/b]\[/color]，我们可否改变Spring这一“默认的行为”呢？答案是肯定的，那就是通过proxy-target-class="true"这个属性，Spring植入增强时，将不管Bean有没有实现接口，统统采用基于扩展子类的方式进行动态代理，也即生成的动态代理是AaaService的子类，那当然就可以赋给AaaService有实例了： \[code="xml"] \[/code] 注意，你需要将CGLib包放到类路径下，因为Spring用它来动态生成代理！以下是我这个小例子的Maven: \[code="xml"] 4.0.0 onlyTest onlyTest 1.0-SNAPSHOT 3.2.3.RELEASE 5.1.25 org.springframework spring-context ${spring.version} org.springframework spring-context-support ${spring.version} org.springframework spring-aop ${spring.version} org.springframework spring-jdbc ${spring.version} mysql mysql-connector-java ${mysql.version} org.aspectj aspectjweaver 1.6.10 \[/code]