一個常見的Spring IOC疑難症狀

Case 
   請看下面的IOC實例: 
   
   1)AaaService實現AaaaInterface接口 
   2)在BaaService中Autowired AaaService 
   
Code 

java

Java代碼  收藏代碼mysql

  1. //1.AaaInterface  spring

  2. package com.test;  sql

  3. public interface AaaInterface {  express

  4.     void method1();  apache

  5. }  app

  6.   

  7. //2.AaaService  maven

  8. package com.test;  ide

  9. public class AaaService implements AaaInterface {  post

  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>  

相關文章
相關標籤/搜索