从一个异常探索spring autowired 的原理

从一个异常探索autowired 的原理。

首先环境是这样的:

public class Boss {

    @Autowired
    private Car car;

}

//@Component 加上这个注释,上面的Boss 的Autowired car就会失败,出现下面的异常
public class Car {
    private String brand;
    private double price;

}

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

    <context:component-scan base-package="com.baobaotao"></context:component-scan>

    <!-- 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 -->
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

    <!-- 移除 boss Bean 的属性注入配置的信息 -->
    <bean id="boss" class="com.baobaotao.Boss"/>
 <!--
    <bean id="office" class="com.baobaotao.Office">
        <property name="officeNo" value="001"/>
    </bean>
    <bean id="car" class="com.baobaotao.Car" scope="singleton">
        <property name="brand" value=" 红旗 CA72"/>
        <property name="price" value="2000"/>
    </bean>-->

</beans>

测试类:

import com.baobaotao.Boss;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml"})
public class AutowiredlTest extends
        AbstractJUnit4SpringContextTests {

    @Autowired
    Boss boss;

    @Test
    public void aaa() {
        System.out.println("boss = " + boss);

    }
}

结果是出现异常:

D:\soft\java\jdk1.7\bin\java -Didea.launcher.port=7533 "-Didea.launcher.bin.path=D:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.1.2\bin" -Dfile.encoding=UTF-8 -classpath "D:\soft\java\jdk1.7\jre\lib\charsets.jar;D:\soft\java\jdk1.7\jre\lib\deploy.jar;D:\soft\java\jdk1.7\jre\lib\ext\access-bridge-64.jar;D:\soft\java\jdk1.7\jre\lib\ext\dnsns.jar;D:\soft\java\jdk1.7\jre\lib\ext\jaccess.jar;D:\soft\java\jdk1.7\jre\lib\ext\localedata.jar;D:\soft\java\jdk1.7\jre\lib\ext\sunec.jar;D:\soft\java\jdk1.7\jre\lib\ext\sunjce_provider.jar;D:\soft\java\jdk1.7\jre\lib\ext\sunmscapi.jar;D:\soft\java\jdk1.7\jre\lib\ext\zipfs.jar;D:\soft\java\jdk1.7\jre\lib\javaws.jar;D:\soft\java\jdk1.7\jre\lib\jce.jar;D:\soft\java\jdk1.7\jre\lib\jfr.jar;D:\soft\java\jdk1.7\jre\lib\jfxrt.jar;D:\soft\java\jdk1.7\jre\lib\jsse.jar;D:\soft\java\jdk1.7\jre\lib\management-agent.jar;D:\soft\java\jdk1.7\jre\lib\plugin.jar;D:\soft\java\jdk1.7\jre\lib\resources.jar;D:\soft\java\jdk1.7\jre\lib\rt.jar;D:\code\ws\spring\hz\spring-learn\target\test-classes;D:\code\ws\spring\hz\spring-learn\target\classes;C:\Users\lkms\.m2\repository\junit\junit\4.12\junit-4.12.jar;C:\Users\lkms\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Users\lkms\.m2\repository\org\springframework\spring-context\4.3.5.RELEASE\spring-context-4.3.5.RELEASE.jar;C:\Users\lkms\.m2\repository\org\springframework\spring-aop\4.3.5.RELEASE\spring-aop-4.3.5.RELEASE.jar;C:\Users\lkms\.m2\repository\org\springframework\spring-beans\4.3.5.RELEASE\spring-beans-4.3.5.RELEASE.jar;C:\Users\lkms\.m2\repository\org\springframework\spring-core\4.3.5.RELEASE\spring-core-4.3.5.RELEASE.jar;C:\Users\lkms\.m2\repository\commons-logging\commons-logging\1.2\commons-logging-1.2.jar;C:\Users\lkms\.m2\repository\org\springframework\spring-expression\4.3.5.RELEASE\spring-expression-4.3.5.RELEASE.jar;C:\Users\lkms\.m2\repository\org\springframework\spring-web\4.3.5.RELEASE\spring-web-4.3.5.RELEASE.jar;C:\Users\lkms\.m2\repository\org\springframework\spring-test\4.3.5.RELEASE\spring-test-4.3.5.RELEASE.jar;D:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.1.2\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain AnnoIoCTest
十一月 11, 2017 2:21:34 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org[email protected]7a277bd2: startup date [Sat Nov 11 14:21:34 CST 2017]; root of context hierarchy
十一月 11, 2017 2:21:34 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
十一月 11, 2017 2:21:35 下午 org.springframework.context.support.ClassPathXmlApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘boss‘: Unsatisfied dependency expressed through field ‘car‘; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.baobaotao.Car‘ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ‘boss‘: Unsatisfied dependency expressed through field ‘car‘; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.baobaotao.Car‘ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1225)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:552)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93)
    at AnnoIoCTest.main(AnnoIoCTest.java:8)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.baobaotao.Car‘ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1474)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1102)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1064)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 20 more

Process finished with exit code 1

spring 的启动过程中会读取配置的xml,注册所有的 beanDefinition,这个是准备过程。 准备完后是 beanfactory 的refresh ,这个时候会 进行注解的处理, 也就是 BeanPostProcessor。 这其中就包含了对 bean 中包含的各种注解的 解析, 比如 Autowired 注解等。 AutowiredAnnotationBeanPostProcessor 的 postProcessPropertyValues 是继承于InstantiationAwareBeanPostProcessor  。 是对它的实现。 如果我们仔细观察这个错误堆栈, 也许我们会从中发现很多很多的细节。

参考:

http://blog.csdn.net/mack415858775/article/details/47721909 写得非常详细,非常好!

时间: 2024-11-10 16:25:22

从一个异常探索spring autowired 的原理的相关文章

Spring @AutoWired实现原理

昨晚在使用JUnit测试AOP实现时,出现一个问题.在JUnit使用@AutoWired注入某一个对象,Bean Factory里面有该接口的多个实现,Spring不报错,而始终注入的是一个实现类的实例.这种只能分析一下Spring @AutoWired的实现原理来解决了. 1. 在JUnit测试用例实现下setter方法,使用setter进行注入2. 在setter方法上添加断点3. 断点跟踪调试 下面是分析过程:------------ @AutoWired注解源码分析: 1. Spring

深入探索spring技术内幕(二): 剖析spring管理Bean的原理与配置

求二叉树的宽度和深度 给定一个二叉树,获取该二叉树的宽度和深度. 例如输入 a / \ b c / \ / \ d e f g 返回3. 详细描述: 接口说明 原型: int GetBiNodeInfo(BiNode &head, unsigned int *pulWidth, unsigned int *pulHeight) 输入参数: head 需要获取深度的二叉树头结点 输出参数(指针指向的内存区域保证有效): pulWidth 宽度 pulHeight 高度 返回值: 0 成功 1 失败

深入探索spring技术内幕(四): 剖析@Resource注解实现原理与注解注入

一.@Resource注解原理 @Resource可以标注在字段或属性的setter方法上 1.  如果指定了name属性, 那么就按name属性的名称装配; 2. 如果没有指定name属性, 那就按照默认的名称查找依赖对象; 3. 如果按默认名称查找不到依赖对象, 那么@Resource注解就会回退到按类型装配; ① 先写一个自己的@MyResource: import java.lang.annotation.Retention; import java.lang.annotation.Re

spring autowired时发生异常情况

spring beanFactory那些就不说了,这次发生这个异常纠结好了好久,网上找了很多资料看,终于发现问题. 自动装配bean注入的时候,如果Spring配置定义了aop声明式事务,类似如下方式 <aop:config>  <aop:pointcut id="serviceMethods2"   expression="execution(public * net.villion.framework..*(..))" />  <a

Spring异步调用原理及SpringAop拦截器链原理

一.Spring异步调用底层原理 开启异步调用只需一个注解@EnableAsync @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(AsyncConfigurationSelector.class) public @interface EnableAsync { /** * Indicate the 'async' annotation type to be detected at

Spring Boot启动原理解析

Spring Boot启动原理解析http://www.cnblogs.com/moonandstar08/p/6550758.html 前言 前面几章我们见识了SpringBoot为我们做的自动配置,确实方便快捷,但是对于新手来说,如果不大懂SpringBoot内部启动原理,以后难免会吃亏.所以这次博主就跟你们一起一步步揭开SpringBoot的神秘面纱,让它不在神秘. 正文 我们开发任何一个Spring Boot项目,都会用到如下的启动类 从上面代码可以看出,Annotation定义(@Sp

[转帖]Spring Cloud底层原理

拜托!面试不要再问我Spring Cloud底层原理 https://mp.weixin.qq.com/s/ZH-3JK90mhnJPfdsYH2yDA 毫无疑问,Spring Cloud 是目前微服务架构领域的翘楚,无数的书籍博客都在讲解这个技术. 不过大多数讲解还停留在对 Spring Cloud 功能使用的层面,其底层的很多原理,很多人可能并不知晓. 因此本文将通过大量的手绘图,给大家谈谈 Spring Cloud 微服务架构的底层原理. 实际上,Spring Cloud 是一个全家桶式的

spring Mvc 执行原理 及 xml注解配置说明 (六)

Spring MVC 执行原理 在 Spring Mvc 访问过程里,每个请求都首先经过 许多的过滤器,经 DispatcherServlet 处理; 一个Spring MVC工程里,可以配置多个的 dispatcherServlet ,每个 DispatcherServlet 可以对应多个的 HandlerMapping ,每个 HandlerMapping 可以有自己的 Interceptor (拦截器). 1. 请求首先 由 前端 DispatcherServlet 捕获: 2. Disp

Spring?IOC设计原理解析:本文乃学习整理参考而来

Spring IOC设计原理解析:本文乃学习整理参考而来 一. 什么是Ioc/DI? 二. Spring IOC体系结构 (1) BeanFactory (2) BeanDefinition 三. IoC容器的初始化 1. XmlBeanFactory(屌丝IOC)的整个流程 2. FileSystemXmlApplicationContext 的IOC容器流程 1.高富帅IOC解剖 2. 设置资源加载器和资源定位 3.AbstractApplicationContext的refresh函数载入