一个常见的Spring IOC疑难症状

Case  
   请看下面的IOC实例: 
   
   1)AaaService实现AaaaInterface接口 
   2)在BaaService中Autowired AaaService 
   
Code  

Java代码   收藏代码
  1. //1.AaaInterface  
  2. package com.test;  
  3. public interface AaaInterface {  
  4.     void method1();  
  5. }  
  6.   
  7. //2.AaaService  
  8. package com.test;  
  9. public class AaaService implements AaaInterface {  
  10.   
  11.     @Override  
  12.     public void method1() {  
  13.         System.out.println("hello");  
  14.     }  
  15.   
  16.     public void method2() {  
  17.         System.out.println("hello");  
  18.     }  
  19. }  
  20.   
  21. //3.BbbService  
  22. package com.test;  
  23.   
  24. import org.springframework.beans.factory.annotation.Autowired;  
  25. import org.springframework.stereotype.Service;  
  26. public class BbbService {  
  27.   
  28.     @Autowired  
  29.     private AaaService aaaService;  
  30.   
  31.     public void method2(){  
  32.         System.out.println("hello method2");  
  33.     }  
  34. }  


Spring XML配置  
Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xmlns:tx="http://www.springframework.org/schema/tx"  
  5.        xmlns:context="http://www.springframework.org/schema/context"  
  6.        xmlns:aop="http://www.springframework.org/schema/aop"  
  7.        xmlns:p="http://www.springframework.org/schema/p"  
  8.        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  9.     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  
  10.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
  11.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
  12.   
  13.     <context:property-placeholder location="classpath*:conf.properties"/>  
  14.     <!--扫描除Controller外的Bean,Controller在MVC层配置-->  
  15.     <context:component-scan base-package="com.test"/>  
  16.   
  17.     <!--数据源-->  
  18.     <bean id="dataSource"  
  19.           class="org.springframework.jdbc.datasource.SingleConnectionDataSource"  
  20.           p:driverClassName="${jdbc.driverClassName}"  
  21.           p:url="${jdbc.url}"  
  22.           p:username="${jdbc.username}"  
  23.           p:password="${jdbc.password}"/>  
  24.   
  25.     <bean id="txManager"  
  26.           class="org.springframework.jdbc.datasource.DataSourceTransactionManager"  
  27.           p:dataSource-ref="dataSource"/>  
  28.   
  29.     <!-- 通过AOP配置的事务管理增强 -->  
  30.     <aop:config >  
  31.         <aop:pointcut id="serviceMethod"  
  32.                       expression="execution(public * com.test..*Service.*(..))"/>  
  33.         <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>  
  34.     </aop:config>  
  35.   
  36.     <tx:advice id="txAdvice" transaction-manager="txManager">  
  37.         <tx:attributes>  
  38.             <tx:method name="*"/>  
  39.         </tx:attributes>  
  40.     </tx:advice>  
  41.     <!--  -->  
  42. </beans>  


启动Spring容器  

Java代码   收藏代码
  1. package com.test;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. public class MainStarter {  
  7.     public static void main(String[] args) {  
  8.         ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");  
  9.         BbbService bbbService = applicationContext.getBean("bbbService", BbbService.class);  
  10.     }  
  11. }  


结果报了以下这堆异常: 
Java代码   收藏代码
  1. 2013-7-25 13:54:08 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons  
  2. 信息: 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  
  3. //重要的信息在这儿!!  
  4. 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)}  
  5.     at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288)  
  6.     at   
  7.     ... 50 more  

上面的异常告诉我们,BbbService Bean创建不了,因为无法Autowired其aaaService的成员变量,说在Spring容器中不存在这个AaaService的Bean. 

分析  

以上是Spring IoC中一个经典的错误,其原因是Spring对Bean的动态代理引起的: 

1)由于在applicationContext.xml中,通过<aop>对所有Service进行事务增强,因此Spring容器会对所有所有XxxService的Bean进行动态代理; 

2)默认情况下,Spring使用基于接口的代理,也即: 
  a)如果Bean类有实现接口,那么Spring自动使用基于接口的代理创建该Bean的代理实例; 
  b)如果Bean类没有实现接口,那么则使用基于子类扩展的动态代理(即CGLib代理); 

3)由于我们的AaaService实现了AaaInterface,所以Spring在生成AaaService类的动态代理Bean时,采用了 
  基于接口的动态代理,该动态代理实例只实现AaaInterface,且该实例不能强制转换成AaaService。 换句话说,AaaService生成的Bean不能赋给AaaService的实例,而只能赋给AaaInterface的实例。  

4)因此,当BbbService希望注入AaaService的成员时,Spring找不到对应的Bean了(因为只有AaaInterface的Bean). 


解决  


方法1  

既然AaaService Bean是被Spring动态代理后改变成了类型,那如果取消引起动态代理的配置,使Spring不会对AaaService动态代理,那么AaaService的Bean类型就是原始的AaaService了: 
Xml代码   收藏代码
  1. <beans>  
  2. ...  
  3.     <!-- 把以下的配置注释掉 -->  
  4.  <!--    <aop:config >  
  5.         <aop:pointcut id="serviceMethod"  
  6.                       expression="execution(public * com.test..*Service.*(..))"/>  
  7.         <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>  
  8.     </aop:config>  
  9.   
  10.     <tx:advice id="txAdvice" transaction-manager="txManager">  
  11.         <tx:attributes>  
  12.             <tx:method name="*"/>  
  13.         </tx:attributes>  
  14.     </tx:advice>-->  
  15.     <!--  -->  
  16. </beans>  


引起Spring对AaaService进行动态代理的<aop>配置注释后,重新启动容器,即可正常启动了。 

但是这里AaaService的方法就不会被事务增强了,这将违背了我们的初衷,因此这种解决方法仅是为了让大家了解到引起IOC问题的根源所在,并没有真正解决问题。 

方法2  

将BbbService的AaaService成员改成AaaInterface: 
Java代码   收藏代码
  1. @Service("bbbService")  
  2. public class BbbService {  
  3.   
  4.     @Autowired  
  5.     private AaaInterface aaaService;//注意这儿,成员类型从AaaService更改为AaaInterface  
  6.   
  7.     public void method2(){  
  8.         System.out.println("hello method2");  
  9.     }  
  10. }  


既然AaaService Bean被植入事务增强动态代理后就变成了AaaInterface的实例,那么干脆我们更改BbbService的成员属性类型,也是可以解决问题的。 

但是这样的话,只能调用接口中拥有的方法 ,在AaaService中定义的方法(如method2())就调用不到了,因为这个代理后的Bean不能被强制转换成AaaService。 

因此,就引出了我们的终极解决办法,请看方法3: 

方法3  

  刚才我们说 “Spring在默认情况下,对实现接口的Bean采用基于接口的代理” ,我们可否改变Spring这一“默认的行为”呢?答案是肯定的,那就是通过proxy-target-class="true"这个属性,Spring植入增强时,将不管Bean有没有实现接口,统统采用基于扩展子类的方式进行动态代理,也即生成的动态代理是AaaService的子类,那当然就可以赋给AaaService有实例了: 

Xml代码   收藏代码
  1. <!-- 注意这儿的proxy-target-class="true" -->  
  2. <aop:config proxy-target-class="true">  
  3.     <aop:pointcut id="serviceMethod"  
  4.                   expression="execution(public * com.test..*Service.*(..))"/>  
  5.     <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>  
  6. </aop:config>  
  7.   
  8. <tx:advice id="txAdvice" transaction-manager="txManager">  
  9.     <tx:attributes>  
  10.         <tx:method name="*"/>  
  11.     </tx:attributes>  
  12. </tx:advice>  


注意,你需要将CGLib包放到类路径下,因为Spring用它来动态生成代理!以下是我这个小例子的Maven: 
Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"  
  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  5.     <modelVersion>4.0.0</modelVersion>  
  6.   
  7.     <groupId>onlyTest</groupId>  
  8.     <artifactId>onlyTest</artifactId>  
  9.     <version>1.0-SNAPSHOT</version>  
  10.   
  11.     <properties>  
  12.        <spring.version>3.2.3.RELEASE</spring.version>  
  13.         <mysql.version>5.1.25</mysql.version>  
  14.     </properties>  
  15.   
  16.     <dependencies>  
  17.   
  18.         <dependency>  
  19.             <groupId>org.springframework</groupId>  
  20.             <artifactId>spring-context</artifactId>  
  21.             <version>${spring.version}</version>  
  22.         </dependency>  
  23.   
  24.         <dependency>  
  25.             <groupId>org.springframework</groupId>  
  26.             <artifactId>spring-context-support</artifactId>  
  27.             <version>${spring.version}</version>  
  28.         </dependency>  
  29.   
  30.         <dependency>  
  31.             <groupId>org.springframework</groupId>  
  32.             <artifactId>spring-aop</artifactId>  
  33.             <version>${spring.version}</version>  
  34.         </dependency>  
  35.   
  36.         <dependency>  
  37.             <groupId>org.springframework</groupId>  
  38.             <artifactId>spring-jdbc</artifactId>  
  39.             <version>${spring.version}</version>  
  40.         </dependency>  
  41.   
  42.         <dependency>  
  43.             <groupId>mysql</groupId>  
  44.             <artifactId>mysql-connector-java</artifactId>  
  45.             <version>${mysql.version}</version>  
  46.         </dependency>  
  47.   
  48.         <dependency>  
  49.             <groupId>org.aspectj</groupId>  
  50.             <artifactId>aspectjweaver</artifactId>  
  51.             <version>1.6.10</version>  
  52.         </dependency>  
  53.   
  54.     </dependencies>  
  55.       
  56. </project>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值