Sping之自动注入-1

2023-11-19

最近终于能静下心来、一步步的学习Java Web开发。在学习的过程中,遇到太多的问题。一开始好些问题真是不知道怎么解决。在这里要非常感谢《Sping In Action》一书的作者,感谢他能写出此书,让我受益匪浅,您辛苦了!吐舌头奋斗


本着“相互学习、共同进步”的原则,从今天开始,决定把自己遇到的问题,以及解决的方法都分享给大家。好以就不废话了,开始今天的分享。


今天在学习Spring以注解方式注入时,报以下错误:

th03::MianRun::run()
一月 21, 2016 11:16:01 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@790f3a9c: startup date [Thu Jan 21 23:16:01 CST 2016]; root of context hierarchy
一月 21, 2016 11:16:01 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [th03/spring.xml]
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testcls1': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: th03.TestCls2 th03.TestCls1.m_cls2; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [th03.TestCls2] 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:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at th03.MainRun.run(MainRun.java:19)
    at kpy.SpringInAction.App.th_run(App.java:22)
    at kpy.SpringInAction.App.main(App.java:18)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: th03.TestCls2 th03.TestCls1.m_cls2; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [th03.TestCls2] 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$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 15 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [th03.TestCls2] 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.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1100)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:960)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:855)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 17 more

我的代码如下:

//TestCls2.java
package th03;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component
public class TestCls2 {
	
	void func1 () {
		System.out.println("TestCls2::func1 ()");
	}

}
TestCls1.java

package th03;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component
public class TestCls1 {
	
	@Autowired
	TestCls2 m_cls2;
	
	void func1 () {
		System.out.println("TestCls1::func1 ()");
		
		m_cls2.func1();
	}
}

主函数为

package th03;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import kpy.SpringInAction.Th00;

public class MainRun implements Th00{
	
	@Autowired
	TestCls1 m_cls;
	
	public void run () {

		System.out.println("th03::MianRun::run()");
		
		ApplicationContext context = new ClassPathXmlApplicationContext("/th03/spring.xml");
		
		this.m_cls  = (TestCls1)context.getBean("testcls1");
		this.m_cls.func1();
	}
}

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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd"
    >

	<!-- 
	<context:annotation-config />
	 -->
	
	<!-- 定义自动注入功能搜索主包名 -->
	<!-- 以下这样配置要报错 
         <context:component-scan base-package="th03.*" />
	 -->
	 <context:component-scan base-package="th03" />
	
	<!--  -->
	<bean id="testcls1" class="th03.TestCls1" />

</beans> 

错误其实就是spring.xml中红色标记的那一句。在一个项目中,这样的配置,th03.*表示th03包以及子包。但不晓得这里为什么不行(这个问题先记着吧,后续再解决吐舌头


另外在MainRun中,已经对TestCls1标记为自动注入了,为什么还要以下这一句。

this.m_cls  = (TestCls1)context.getBean("testcls1");
个人解理是,由于在实现化MainRun这个类的实例时,还没有加载spring.xml,所以Java虚拟机并不知道怎么去实例化,因此用null去注入的(可以在类构造中进行new,再检查成员是否为null)。所以才在加载XML后,加了这一句。

另外,经测试,把这一句换成

this.m_cls = new TestCls1();

也是不行的。经@Autowired标注后的对象,已经注解包装后的类型,不能用原始类型(这里的TestCls1)去赋值。这纯属个人对于C++方面的知识的猜想,后续看了@autowired源码就能确认了吧。


注意:

自动注入功能,需要经spring配置文件中添加

xmlns:context="http://www.springframework.org/schema/context"

这个,不然后抛出以下异常

Caused by: org.xml.sax.SAXParseException; lineNumber: 23; columnNumber: 49; 元素 "context:component-scan" 的前缀 "context" 未绑定。


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Sping之自动注入-1 的相关文章

随机推荐

  • 高德地图打点获取点的坐标和名称

    一 首先引入地图 代码在最后 二 然后是打点获取坐标和名称的方法 代码在最后 重点 如果不加上密钥的话可能会得不到数据名称 你想要的代码来了 密钥 window AMapSecurityConfig securityJsCode 你申请ke
  • GraphPad Prism 9.2 Mac 2021最新安装使用教程

    GraphPad Prism集生物统计 化学统计 以及科技绘图于一身 其中医学所能用到的绘图需要它几乎都能满足 Prism 现在被各种生物学家以及社会和物理科学家广泛使用 超过110个国家的超过20万名科学家依靠 Prism 来分析 绘制和
  • SpringBoot学习遇到的问题(1) - 配置文件有日志的debug模式等配置项,为什么不起作用...

    这个问题困扰我近乎两天 通过查找N多资料后终于解决 写下来共享给大家 logging level root DEBUG 一系列的日志配置项 都不起作用的原因是springboot启动加载不到src main resources下的配置文件a
  • 那些踩过的declared implicitly的坑

    缺少头文件 我的本意是想做串口打印进行调试 于是我在usart c中重写了这两个函数 这里顺便记录下如何串口打印 usart c中 int fputc int ch FILE f HAL UART Transmit huart1 uint8
  • 2023计算机四非保研(复试:东北大学,成电,西电,浙软,中海洋,天大)

    文章目录 个人情况 夏令营情况 预推免情况 进入复试 中国海洋大学 学硕 浙大软院 专硕 天津大学智算 专硕 中科院网络中心 专硕 西电网安院 学硕 东北大学计算机 学硕 成电计算机 专硕 最终offer 感想 个人情况 本科学校 西北某四
  • firmware-mod-kit工具安装和使用说明

    一 firmware mod kit工具的安装 firmware mod kit工具的功能和binwalk工具的类似 其实firmware mod kit工具在功能上有调用binwalk工具提供的功能以及其他的固件解包工具的整合 下载fir
  • pp-human在rk3588上部署

    https github com leeguandong Yolov5 rknnlite2https github com leeguandong Yolov5 rknnlite2 这是我在paddledetection和rknn官方基础上
  • Jmeter使用JDBC对数据库压测

    背景说明 压测除了全链路压测外 有时候也需要对指定服务进行性能测试 这里以jmeter工具对数据库进行压测说明 压测不同数据库需要安装不同的数据库驱动 这里以mysql为例进行压测 步骤一 数据库驱动安装 1 进入mysql官网 根据不同m
  • 课程设计心得_关于switch输入字母进入死循环问题

    做C语言课程设计时 采用了大量的switch 在后期找bug时 当输入字符类型时 如a 之类的 程序进入了死循环 但又不想换成其他的 主要是懒 不想大量改动 void menu windows int n system cls fflush
  • Python3 字典

    字典是另一种可变容器模型 且可存储任意类型对象 字典的每个键值 key gt value 对用冒号 分割 每个对之间用逗号 分割 整个字典包括在花括号 中 格式如下所示 注意 dict 作为 Python 的关键字和内置函数 变量名不建议命
  • 安全运维之Resin应用服务器中间件安装使用与安全配置

    本章目录 0x00 快速入门 0x01 Resin安装 0x02 Resin配置文件 0x03 Resin应用 0x04 Security 0x05 Help 附录补充 1 Resin 日志记录之format配置详解 原文地址 https
  • 登入服务器bmc_如何使用 BMCTool 远程管理 PowerEdge C 系列服务器

    文章内容 症状 本文介绍了如何使用 BMCTool 管理 PowerEdge C 系列服务器 BMC 工具旨在压缩和改进 IPMITool 的功能 可从poweredgec dell com下载 需要安装 OpenIPMI 和 IPMITo
  • redis学习笔记(七):redis常见问题和解决方案

    目录 一 缓存穿透 1 基本介绍 2 解决方案 1 布隆过滤器 2 缓存空对象 3 参数校验 4 对比 二 缓存击穿 1 基本介绍 2 解决方案 1 互斥锁 2 永不过期 3 两种方案对比 三 缓存雪崩 1 基本介绍 2 解决方案 1 过期
  • ODBC连接ORACLE数据库的设置

    一 建立服务名1 选择 Net8 Configuration Assistant 选择 本地网络服务名配置 2 选择 添加 3 选择 Oracle 8i数据库或服务 4 输入服务名 此为远程数据库已经定制好的数据库服务名字 比如 ORCL
  • python map和lambda

    map和lambda 前言 一 map 二 lambda 三 map和lambda的使用 前言 一 map map是python的内置函数 根据提供的函数对指定序列做映射 map function literation function 函
  • ngrok服务端搭建并使用docker解放80端口

    start 前言 为什么要搭建ngrok服务端 为什么使用docker 1 开发环境下调试微信公众号使用 要求80端口 2 ngrok配置中要指定 http的端口 如果指定80端口的话 会和nginx抢端口 nginx肯定比ngrok重要
  • Ajax核心技术之XMLHttpRequest对象

    XMLHttpRequest对象到底是什么 跟Ajax到底有什么联系 在了解它之前还是要先了解一下Ajax的功能 与以往的技术不同 Ajax是为了实现异步操作 那么关于异步 好像一个管理者安排好一个项目计划后 将这个项目交给下属去做 而自己
  • 揭秘win10系统CPU占用100%的真正原因/找出那些罪魁祸首

    经常会有 Win10 用户反应 电脑没有运行太多程序 但是在任务管理器中 经常可以看到电脑CPU占用率却一直居高不下 那么 CPU占用100 的正真原因是什么呢 下面小编收集了一些针对CPU占用过高的原因及解决办法 这些可能就是导致你CPU
  • Spring Boot 快速入门、开发环境热部署

    SpringBoot快速上手 准备工作 我们将学习如何快速的创建一个Spring Boot应用 并且实现一个简单的Http请求处理 通过这个例子对Spring Boot有一个初步的了解 并体验其结构简单 开发快速的特性 我的环境准备 jav
  • Sping之自动注入-1

    最近终于能静下心来 一步步的学习Java Web开发 在学习的过程中 遇到太多的问题 一开始好些问题真是不知道怎么解决 在这里要非常感谢 Sping In Action 一书的作者 感谢他能写出此书 让我受益匪浅 您辛苦了 本着 相互学习