@Autowired默认按类型装配,假设我在personDao 字段上加了@Autowired注解,那么就会默认取personDao 字段的类型在Spring容器中寻找与这个类型匹配的bean,寻找到相应的bean之后就会把这个bean注入到该字段上来。

默认情况下必需要求依赖对象必须存在。假设要同意null
值,能够设置它的required属性为false,如:@Autowired(required=false) 。假设我们想使用名称装配能够结合@Qualifier注解进行使用,例如以下:

@Autowired() @Qualifier("personDao")
private PersonDao personDao ;

beans.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"
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"> <context:annotation-config/> <bean id="personDao" class="xjj.dao.impl.PersonDaoBean"></bean>
<bean id="personService" class="xjj.service.impl.PersonServiceBean" ></bean>
</beans>

首先看看默认按类型装配:PersonServiceBean.java

package xjj.service.impl;

import org.springframework.beans.factory.annotation.Autowired;

import xjj.dao.PersonDao;
import xjj.service.PersonService; public class PersonServiceBean implements PersonService {
@Autowired
private PersonDao personDao; public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
} public void save(){
personDao.add();
}
}

在測试类SpringTest2.java中,我们调用personservice的save方法,假设装配失败,会出现空指针异常

如今我们看一下測试结果:注入成功

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamVvZmV5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

接下来我们验证一下,结合@Qualifier注解按名称装配

@Autowired @Qualifier("personDaoxxxx")
private PersonDao personDao;

beans.xml中bean的名称没有与注入名称一致的bean,就会发生异常

<bean id="personDao" class="xjj.dao.impl.PersonDaoBean"></bean>
<bean id="personService" class="xjj.service.impl.PersonServiceBean" ></bean>

结果:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personService': Autowiring of fields failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private xjj.dao.PersonDao xjj.service.impl.PersonServiceBean.personDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [xjj.dao.PersonDao] is defined: Unsatisfied dependency of type [interface xjj.dao.PersonDao]: expected at least 1 matching bean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:243)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:959)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at junit.test.SpringTest2.instanceSpring(SpringTest2.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private xjj.dao.PersonDao xjj.service.impl.PersonServiceBean.personDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [xjj.dao.PersonDao] is defined: Unsatisfied dependency of type [interface xjj.dao.PersonDao]: expected at least 1 matching bean
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:435)
at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:240)
... 39 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [xjj.dao.PersonDao] is defined: Unsatisfied dependency of type [interface xjj.dao.PersonDao]: expected at least 1 matching bean
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:613)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:412)
... 41 more

假设我们把两个bean名称改成一致,就会注入成功

<bean id="personDaoxxxx" class="xjj.dao.impl.PersonDaoBean"></bean>
<bean id="personService" class="xjj.service.impl.PersonServiceBean" ></bean>

结果:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvamVvZmV5/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

Spring2.5学习3.3_@Autowire注解实现手动装配的更多相关文章

  1. (转)@Autowire注解与自动装配

    http://blog.csdn.net/yerenyuan_pku/article/details/52860713 前面我们已经学会使用@Resource注解注入属性,并且我们还编码剖析了@Res ...

  2. Spring学习记录(十一)---使用注解和自动装配

    Spring支持用注解配置Bean,更简便. 上面的组件,是根据实际情况配的.比如写的一个类,是做业务处理的,那就用注解@Service表示服务层组件,以此类推.将整体分成不同部分. 要在xml加入c ...

  3. spring autoWire注解和@resource注解区别

    1.autoWire注解主要是按类型匹配.因为autowire的扫描机制,是按照接口类型来扫描bean的. 而JSR250 @resource注解是通过名称扫描注入的. @autowire注解的扫描方 ...

  4. spring autoWire注解

    1.autowire注解,可以用来获得applicationContext,ResourceLoader,BeanFactory的注入 autoWire会获得相应资源 2.autoWire注解还可以用 ...

  5. idea下使用autowire注解注入对象,结果初始化不到类

    如果idea下使用autowire注解注入对象,结果初始化不到类,明明使用快捷键alt+insert是可以找到该注入的对象的. 而我们在使用的时候,缺报错了??? 注意,当我们在注入对象的时候,我们留 ...

  6. 跟着刚哥学习Spring框架--通过注解方式配置Bean(四)

    组件扫描:Spring能够从classpath下自动扫描,侦测和实例化具有特定注解的组件. 特定组件包括: 1.@Component:基本注解,识别一个受Spring管理的组件 2.@Resposit ...

  7. springmvc学习笔记(13)-springmvc注解开发之集合类型參数绑定

    springmvc学习笔记(13)-springmvc注解开发之集合类型參数绑定 标签: springmvc springmvc学习笔记13-springmvc注解开发之集合类型參数绑定 数组绑定 需 ...

  8. Hibernate学习一:Hibernate注解CascadeType

    http://zy19982004.iteye.com/blog/1721846 ———————————————————————————————————————————————————————— Hi ...

  9. APUE学习笔记3_文件IO

    APUE学习笔记3_文件IO Unix中的文件IO函数主要包括以下几个:open().read().write().lseek().close()等.这类I/O函数也被称为不带缓冲的I/O,标准I/O ...

随机推荐

  1. ORACLE存储过程笔记3

    ORACLE存储过程笔记3 流程控制 1.条件   if expression thenpl/sql or sqlend if;   if expression thenpl/sql or sqlel ...

  2. javacoo/CowSwing 丑牛迷你采集器

    丑牛迷你采集器是一款基于Java Swing开发的专业的网络数据采集/信息挖掘处理软件,通过灵活的配置,可以很轻松迅速地从 网页上抓取结构化的文本.图片.文件等资源信息,可编辑筛选处理后选择发布到网站 ...

  3. Codeforces 437C The Child and Toy(贪心)

    题目连接:Codeforces 437C  The Child and Toy 贪心,每条绳子都是须要割断的,那就先割断最大值相应的那部分周围的绳子. #include <iostream> ...

  4. 前序 中序 后序 遍历 递归 非递归算法 java实现

    前序遍历 非递归 public void preordernorec(TreeNode root){ //System.out.println("先序遍历(非递归):"); //用 ...

  5. 【转】如何在CentOS/RHEL中安装基于Web的监控系统 linux-das

    Linux-dash是一款为Linux设计的基于Web的轻量级监控面板.这个程序会实时显示各种不同的系统属性,比如CPU负载.RAM使用率.磁盘使用率.网速.网络连接.RX/TX带宽.登录用户.运行的 ...

  6. saltstack:使用教程之一安装及客户端返回写入MySQL

    saltstack使用教程: 1.安装: 需要epel的yum源,没有的话把下面的复制并新建个文件 /etc/yum.repos.d/epel.repo 粘贴即可: [epel] name=Extra ...

  7. RPC通信框架——RCF介绍(替换COM)

    阅读目录 RPC通信框架 为什么选择RCF 简单的性能测试 参考资料 总结 现有的软件中用了大量的COM接口,导致无法跨平台,当然由于与Windows结合的太紧密,还有很多无法跨平台的地方.那么为了实 ...

  8. Integral Promotions整数提升和符号扩展(char,unsigned char,signed char)

    以下来自msdn: Objects of an integral type can be converted to another wider integral type (that is, a ty ...

  9. CSS简介和CSS选择器

    <pre name="code" class="html">Css 简洁 css 选择器 标签选择器 类选择器 ID选择器 Css 层叠样式表 Ca ...

  10. 四大流行的java连接池之BoneCP篇

    BoneCP 是一个开源的快速的 JDBC 连接池.BoneCP很小,只有四十几K(运行时需要log4j和Google Collections的支持,这二者加起来就不小了),而相比之下C3P0 要六百 ...