一个常见的Spring IOC疑难症状

2023-11-17

[b][size=x-large]Case[/size][/b]
请看下面的IOC实例:

1)AaaService实现AaaaInterface接口
2)在BaaService中Autowired AaaService

[b][size=large]Code[/size][/b]


//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");
}
}


[b][size=large]Spring XML配置[/size][/b]

<?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>


[b][size=large]启动Spring容器[/size][/b]


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.

[b][size=x-large]分析[/size][/b]

以上是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。[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了:

<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问题的根源所在,并没有真正解决问题。

[b][size=large]方法2[/size][/b]

将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:

[b][size=large]方法3[/size][/b]

刚才我们说[color=red][b]“Spring在默认情况下,对实现接口的Bean采用基于接口的代理”[/b][/color],我们可否改变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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

一个常见的Spring IOC疑难症状 的相关文章

随机推荐

  • 必看的知识

    学习路线 必看的知识 Spring实战 Spring 4 x企业应用开发实战 深入分析Java Web技术内幕 修订版 Effective Java Thinking in Java Java核心技术 Core Java Thinking
  • 赫拉(hera)分布式任务调度系统

    相关介绍 赫拉 hera 分布式任务调度系统之架构 基本功能 一 赫拉 hera 分布式任务调度系统之项目启动 二 赫拉 hera 分布式任务调度系统之开发中心 三 赫拉 hera 分布式任务调度系统之版本 四 赫拉 hera 分布式任务调
  • 修正了一个通信bug

    该BUG导致用户在打开webchat使用界面时不会读取联系人UPT 有时候刷新界面后会解决这个问题 经过发现是判断webchat是否存在在线用户以便于打印在线和离线联系人的分支结构出错 现在bug已经解除 同时解决了一个UPT串截断出错的b
  • java实现文件的断点续传的下载

    java的断点续传是基于之前java文件下载基础上的功能拓展 首先设置一个以线程ID为名的下载进度文件 每一次下载的进度会保存在这个文件中 下一次下载的时候 会根据进度文件里面的内容来判断下载的进度 package com ldw mult
  • Win10/Win11子系统(一)——wsl2+Ubuntu20.04安装记录

    windows子系统Ubuntu20 04安装过程记录 前言 一 安装前准备 二 开始安装 三 更换镜像源 四 安装图形化界面 五 警告处理 六 迁移子系统 前言 我和我最后的倔强 坚持不换windows的口号被现实打败了 装双系统会影响到
  • Hive SQL使用中遇到的问题与解决方案(持续更新

    近期 因统计分析 数据处理的工作需求 经常使用Hive SQL 因此记录遇到的一些问题 1 desc formatted 表名 确定表的信息 行 列 存储路径 在确定Hive 数据仓库中表的存储路径时 很有帮助 2 SQL GROUP BY
  • 【MedusaSTears】IntelliJ IDEA 自动生成方法注释模板设置(入参每行1个如图)

    快捷键 按键 按键 按键tab 效果图 设置方式 参考资料 https blog csdn net yuruixin china article details 80933835 我也是参考这个文章设置的 只不过我改了一些其它的内容 修改如
  • “疫情”防控时期大势所趋,智慧社区尽显“智慧”迎来新的发展热潮

    近期 国内新冠肺炎疫情在各地再次反扑 各种变异毒株 境外输入压力让疫情防控变的更加严峻 社区防控是第一道防线 进出小区人员登记 出示健康码 测量体温 居家隔离等是每个社区都要面临的防控压力 但是如果对社区内的居民不能精确管理 就会导致很多的
  • 1234. 替换子串得到平衡字符串

    有一个只含有 Q W E R 四种字符 且长度为 n 的字符串 假如在该字符串中 这四个字符都恰好出现 n 4 次 那么它就是一个 平衡字符串 给你一个这样的字符串 s 请通过 替换一个子串 的方式 使原字符串 s 变成一个 平衡字符串 你
  • Markdown预览 代码块自动化加代码行数-VSCode

    Markdown预览 代码块自动化加代码行数 VSCode 官方地址 https shd101wyy github io markdown preview enhanced zh cn markdown basics id 代码行数 第一步
  • JToolBarTest JToolBar 的一个测试类

    package com test JToolBarTest import javax swing JButton import javax swing JFrame import javax swing JToolBar public cl
  • python笔记:变量赋值与注意事项

    1 单个变量赋值 a 变量未赋值会报错 a 1 正确写法 2 多个变量赋值 方法1 a b c 1 方法2 a b c 1 1 1 print a b c 1 1 1 3 基本变量类型 五大类 字符串 string 数字 Numeric 列
  • 第1章 NumPy基础

    为何第1章介绍NumPy基础 在机器学习和深度学习中 图像 声音 文本等首先要数字化 如何实现数字化 数字化后如何处理 这些都涉及NumPy NumPy是数据科学的通用语言 它是科学计算 矩阵运算 深度学习的基石 PyTorch中的重要概念
  • 分布式消息队列RocketMQ--事务消息--解决分布式事务的最佳实践

    分布式消息队列RocketMQ 事务消息 解决分布式事务的最佳实践 标签 事务消息exactlyRocketMQKafka分布式消息队列 2016 12 23 22 08 7789人阅读 评论 8 收藏 举报 分类 分布式消息队列Rocke
  • Windows Server2012R2 VisualSVN3.9.7-Server在线修改密码搭建

    经过核验 按下面这样的方式去升级 从3 0 0升级到3 9 7 同时支持用户通过web界面修改密码 每个用户忘记密码要管理员来修改 工作量不大 但真的是耗时费力 还不讨好 1 安装软件准备 1 1 软件准备 1 Windows Server
  • 自动化测试系列 —— UI自动化测试

    UI 测试是一种测试类型 也称为用户界面测试 通过该测试 我们检查应用程序的界面是否工作正常或是否存在任何妨碍用户行为且不符合书面规格的 BUG 了解用户将如何在用户和网站之间进行交互以执行 UI 测试至关重要 通过执行 UI 测试 测试人
  • 【数据结构】串

    串 串的顺序实现 简单的模式匹配算法 KMP算法 KMP算法的进一步优化 串的顺序实现 初始化 define MaxSize 50 typedef char ElemType 顺序存储表示 typedef struct ElemType d
  • Klocwork安装

    简单介绍一下Klocwork在windows下的安装 操作系统是win7 Klocwork的版本是10 0 第一步 由于Klocwork的安装程序已十分成熟 所以在安装之前不需要什么准备共走 双击Klocwork的安装包 会出现下图的安装引
  • java实现顺序表

    顺序表是在计算机内存中以数组的形式保存的线性表 是指用一组地址连续的存储单元依次存储数据元素的线性结构 线性表采用顺序存储的方式存储就称之为顺序表 顺序表是将表中的结点依次存放在计算机内存中一组地址连续的存储单元中 1 创建一个顺序表 cl
  • 一个常见的Spring IOC疑难症状

    b size x large Case size b 请看下面的IOC实例 1 AaaService实现AaaaInterface接口 2 在BaaService中Autowired AaaService b size large Code