Case
请看下面的IOC实例:
1)AaaService实现AaaaInterface接口
2)在BaaService中Autowired AaaService
Code
java
//1.AaaInterface spring
package com.test; sql
public interface AaaInterface { express
void method1(); apache
} app
//2.AaaService maven
package com.test; ide
public class AaaService implements AaaInterface { post
@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");
}
}
Spring XML配置
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:property-placeholder location="classpath*:conf.properties"/>
<!--扫描除Controller外的Bean,Controller在MVC层配置-->
<context:component-scan base-package="com.test"/>
<!--数据源-->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.SingleConnectionDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<!-- 经过AOP配置的事务管理加强 -->
<aop:config >
<aop:pointcut id="serviceMethod"
expression="execution(public * com.test..*Service.*(..))"/>
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- //////////////////////////////////////////////// -->
</beans>
启动Spring容器
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);
}
}
结果报了如下这堆异常:
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
上面的异常告诉咱们,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了:
<beans>
...
<!-- 把如下的配置注释掉 -->
<!-- <aop:config >
<aop:pointcut id="serviceMethod"
expression="execution(public * com.test..*Service.*(..))"/>
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>-->
<!-- //////////////////////////////////////////////// -->
</beans>
引发Spring对AaaService进行动态代理的<aop>配置注释后,从新启动容器,便可正常启动了。
可是这里AaaService的方法就不会被事务加强了,这将违背了咱们的初衷,所以这种解决方法仅是为了让你们了解到引发IOC问题的根源所在,并无真正解决问题。
方法2
将BbbService的AaaService成员改为AaaInterface:
@Service ("bbbService")
public class BbbService {
@Autowired
private AaaInterface aaaService;//注意这儿,成员类型从AaaService更改成AaaInterface
public void method2(){
System.out.println("hello method2");
}
}
既然AaaService Bean被植入事务加强动态代理后就变成了AaaInterface的实例,那么干脆咱们更改BbbService的成员属性类型,也是能够解决问题的。
可是这样的话,只能调用接口中拥有的方法 ,在AaaService中定义的方法(如method2())就调用不到了,由于这个代理后的Bean不能被强制转换成AaaService。
所以,就引出了咱们的终极解决办法,请看方法3:
方法3
刚才咱们说“Spring在默认状况下,对实现接口的Bean采用基于接口的代理”,咱们能否改变Spring这一“默认的行为”呢?答案是确定的,那就是经过proxy-target-class="true"这个属性,Spring植入加强时,将无论Bean有没有实现接口,通通采用基于扩展子类的方式进行动态代理,也即生成的动态代理是AaaService的子类,那固然就能够赋给AaaService有实例了:
<!-- 注意这儿的proxy-target-class="true" -->
<aop:config proxy-target-class="true">
<aop:pointcut id="serviceMethod"
expression="execution(public * com.test..*Service.*(..))"/>
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice"/>
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
注意,你须要将CGLib包放到类路径下,由于Spring用它来动态生成代理!如下是我这个小例子的Maven:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>onlyTest</groupId>
<artifactId>onlyTest</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.version>3.2.3.RELEASE</spring.version>
<mysql.version>5.1.25</mysql.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.10</version>
</dependency>
</dependencies>
</project>