Spring使用@Autowired注解自动装配

在上一篇 Spring学习(三)-----Spring自动装配Beans示例中,它会匹配当前Spring容器任何bean的属性自动装配。在大多数情况下,你可能只需要在特定的 bean 自动装配属性。
在Spring中,可以使用 @Autowired 注解通过setter方法,构造函数或字段自动装配Bean。此外,它可以在一个特定的bean属性自动装配。

注 @Autowired注解是通过匹配数据类型自动装配Bean。

请参见下面的完整的例子来演示如何使用@Autowired。

1. Beans

一个 Customer bean 在bean配置文件中声明。稍后,您将使用 “@Autowired” 来自动装配一个Person bean。
package com.yiibai.common;

public class Customer
{
//you want autowired this field.
private Person person; private int type;
private String action; //getter and setter method } <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="CustomerBean" class="com.yiibai.common.Customer">
<property name="action" value="buy" />
<property name="type" value="1" />
</bean> <bean id="PersonBean" class="com.yiibai.common.Person">
<property name="name" value="yiibai" />
<property name="address" value="address 123" />
<property name="age" value="28" />
</bean> </beans>

2. 注册AutowiredAnnotationBeanPostProcessor

要启用@Autowired,必须注册“AutowiredAnnotationBeanPostProcessor',你可以用两种方式做到这一点:

1. Include <context:annotation-config />

添加 Spring 上下文和<context:annotation-config />在bean配置文件中。
<beans
//...
xmlns:context="http://www.springframework.org/schema/context"
//...
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
//... <context:annotation-config />
//...
</beans>

下面是完整的实例

<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="CustomerBean" class="com.yiibai.common.Customer">
<property name="action" value="buy" />
<property name="type" value="1" />
</bean> <bean id="PersonBean" class="com.yiibai.common.Person">
<property name="name" value="yiibai" />
<property name="address" value="address ABC" />
<property name="age" value="29" />
</bean> </beans>

2.  包含 AutowiredAnnotationBeanPostProcessor

直接在bean配置文件包含“AutowiredAnnotationBeanPostProcessor”。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean id="CustomerBean" class="com.yiibai.common.Customer">
<property name="action" value="buy" />
<property name="type" value="1" />
</bean> <bean id="PersonBean" class="com.yiibai.common.Person">
<property name="name" value="yiibai" />
<property name="address" value="address ABC" />
<property name="age" value="29" />
</bean> </beans>

3. @Autowired示例

现在,你可以通过 @Autowired 自动装配 bean,它可以在 setter 方法,构造函数或字段中使用。
1. @Autowired setter 方法
package com.yiibai.common;

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

public class Customer
{
private Person person;
private int type;
private String action;
//getter and setter methods @Autowired
public void setPerson(Person person) {
this.person = person;
}
}
2. @Autowired 构造方法
package com.yiibai.common;

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

public class Customer
{
private Person person;
private int type;
private String action;
//getter and setter methods @Autowired
public Customer(Person person) {
this.person = person;
}
}
3. @Autowired 字段
package com.yiibai.common;

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

public class Customer
{
@Autowired
private Person person;
private int type;
private String action;
//getter and setter methods
}
上面的例子会自动装配“PersonBean”到Customer的person属性。

执行它

package com.yiibai.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"}); Customer cust = (Customer)context.getBean("CustomerBean");
System.out.println(cust); }
}

输出

Customer [person=Person [name=YiibaiA], type=1, action=buy]
依赖检查

默认情况下,@Autowired将执行相关检查,以确保属性已经装配正常。当Spring无法找到匹配的Bean装配,它会抛出异常。要解决这个问题,可以通过 @Autowired 的“required”属性设置为false来禁用此检查功能。

package com.yiibai.common;

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

public class Customer
{
@Autowired(required=false)
private Person person;
private int type;
private String action;
//getter and setter methods
}
在上面的例子中,如果Spring不能找到一个匹配的Bean,person属性将不设定。

@Qualifier

@Qualifier注解我们用来控制bean应在字段上自动装配。例如,具有两个类似的 person bean 配置文件。
<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="CustomerBean" class="com.yiibai.common.Customer">
<property name="action" value="buy" />
<property name="type" value="1" />
</bean> <bean id="PersonBean1" class="com.yiibai.common.Person">
<property name="name" value="yiibai-1" />
<property name="address" value="address-1" />
<property name="age" value="29" />
</bean> <bean id="PersonBean2" class="com.yiibai.common.Person">
<property name="name" value="yiibai-2" />
<property name="address" value="address-2" />
<property name="age" value="28" />
</bean> </beans>
Spring知道哪个 bean 应当装配?
为了解决这个问题,可以使用 @Qualifier 自动装配一个特定的 bean,例如,
package com.yiibai.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; public class Customer
{
@Autowired
@Qualifier("PersonBean1")
private Person person;
private int type;
private String action;
//getter and setter methods
}

这意味着,“PersonBean1” bean被自动装配到customer的person属性。

总结

这@Autowired注解非常灵活,功能强大,绝对比bean配置文件的“autowire”属性要更好。

Spring学习(六)-----Spring使用@Autowired注解自动装配的更多相关文章

  1. Spring学习(9)--- @Autowired注解(二)

    可以使用@Autowired注解那些众所周知的解析依赖性接口,比如:BeanFactory,ApplicationContext,Environment,ResourceLoader,Applicat ...

  2. Spring学习(8)--- @Autowired注解(一)

    可以将@Autowired注解为“传统”的setter方法 package com.mypackage; import org.springframework.beans.factory.annota ...

  3. Spring学习七----------Bean的配置之自动装配

    © 版权声明:本文为博主原创文章,转载请注明出处 Bean的自动装配(Autowiring) no:不启用自动装配,此时需要手动注入.参考:Spring学习三----------注入方式 defaul ...

  4. spring学习 六 spring与mybatis整合

    在mybatis学习中有两种配置文件 :全局配置文件,映射配置文件.mybatis和spring整合,其实就是把mybatis中的全局配置文件的配置内容都变成一个spring容器的一个bean,让sp ...

  5. spring框架应用系列一:annotation-config自动装配

    本文系作者原创,转载请注明出处:http://www.cnblogs.com/further-further-further/p/7716678.html 解决问题 通过spring XML配置文件, ...

  6. Spring学习笔记之依赖的注解(2)

    Spring学习笔记之依赖的注解(2) 1.0 注解,不能单独存在,是Java中的一种类型 1.1 写注解 1.2 注解反射 2.0 spring的注解 spring的 @Controller@Com ...

  7. Spring学习(十一)-----Spring使用@Required注解依赖检查

    Spring学习(九)-----Spring依赖检查 bean 配置文件用于确定的特定类型(基本,集合或对象)的所有属性被设置.在大多数情况下,你只需要确保特定属性已经设置但不是所有属性.. 对于这种 ...

  8. Spring(三):bean的自动装配

    Bean的自动装配 自动装配是Spring满足bean依赖的一种方式. Spring会在上下文中自动寻找,并自动给bean装配属性 Spring中三种装配方式 在xml中显式的配置. 在java中显式 ...

  9. 大厂面试官问你META-INF/spring.factories要怎么实现自动扫描、自动装配?

    大厂面试官问你META-INF/spring.factories要怎么实现自动扫描.自动装配?   很多程序员想面试进互联网大厂,但是也有很多人不知道进入大厂需要具备哪些条件,以及面试官会问哪些问题, ...

随机推荐

  1. LayIM.AspNetCore Middleware 开发日记(四)主角登场(LayIM介绍)

    前言 在前几篇中已经初步介绍了开发AspNetCore中间件的一些基础知识,不过都没有很深入的去研究,后续还是需要去看看源码.本篇呢,终于有点开头的味道了,就是要介绍LayIM了,其实标题写的是主角, ...

  2. ethereumjs/ethereumjs-blockchain-2-test

    https://github.com/ethereumjs/ethereumjs-blockchain/tree/master/test 'use strict' const test = requi ...

  3. iOS沙盒目录文件操作

    简介 沙盒(NSHomeDirectory())中总共有四个文件夹,documents.tmp.app.Library; 手动保存的文件在documents文件里; Nsuserdefaults保存的 ...

  4. 部署Jar包到远程Maven仓库

    在使用maven开发工程时,模块A可能会依赖模块B的jar包,如果两个模块都是在一个工程里,只需要在模块A的pom文件中加入模块B的依赖信息,模块A就可以加载模块B的jar包.但如果模块A与模块B在不 ...

  5. JNI由浅入深_9_JNI 异常处理

    1 .本地代码中如何缓存和抛出异常 下面的代码中演示了如何声明一个会抛出异常的本地方法.CatchThrow这个类声明了一个会抛出IllegalArgumentException异常的名叫doit的本 ...

  6. .Net Core应用程序发布时不同方式的差别

    .Net Core的文档更新的真是快..每次看的时候都觉得之前是不是梦游看的...每次发布应用程序的时候都要翻看下文档..至少rid是死活记不住.还是留个RID的索引吧..还有发布的索引 ,这样就好复 ...

  7. Asp.net MVC使用FormsAuthentication,MVC和WEB API可以共享身份认证 (转载)

    在实际的项目应用中,很多时候都需要保证数据的安全和可靠,如何来保证数据的安全呢?做法有很多,最常见的就是进行身份验证.验证通过,根据验证过的身份给与对应访问权限.同在Web Api中如何实现身份认证呢 ...

  8. 客户端对象模型之Excel数据导入到列表

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <t ...

  9. 微服务—熔断器Hystrix

    前言在微服务架构中,我们将系统拆分成了一个个的服务单元,各单元应用间通过服务注册与发现的方式互相依赖. 由于每个单元都在不同的进程中运行,依赖通过远程调用的方式执行,这样就有可能因为网络原因或是依赖服 ...

  10. C#设计模式 —— 工厂模式

    . 工厂模式同样是项目中最常用的设计模式,工厂模式中又分为简单工厂,工厂方法,抽象工厂.下面我们由简单的开始逐一介绍. 1.简单工厂模式 简单工厂又被称为静态工厂,在设计模式中属于创建型模式.主要解决 ...