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. D、CSL 的字符串 【栈+贪心】 (“新智认知”杯上海高校程序设计竞赛暨第十七届上海大学程序设计春季联赛)

    题目传送门:https://ac.nowcoder.com/acm/contest/551#question 题目描述 CSL 以前不会字符串算法,经过一年的训练,他还是不会……于是他打算向你求助. ...

  2. Infiniband基本知识

    InfiniBand架构是一种支持多并发链接的“转换线缆”技术,在这种技术中,每种链接都可以达到2.5 Gbps的运行速度.这种架构在一个链接的时候速度是500 MB/秒,四个链接的时候速度是2 GB ...

  3. MYSQL统计

    今天  select * from 表名 where to_days(时间字段名) = to_days(now());  昨天  SELECT * FROM 表名 WHERE TO_DAYS( NOW ...

  4. cesium.js 设置缩放最大最小限制

    viewer.scene.screenSpaceCameraController.minimumZoomDistance = 1200;viewer.scene.screenSpaceCameraCo ...

  5. PyTorch Softmax

    PyTorch provides 2 kinds of Softmax class. The one is applying softmax along a certain dimension. Th ...

  6. 并发编程(三)------并发类容器Copy-On-Write容器

    Copy-On-Write简称COW,是一种用于程序设计中的优化策略.JDK里的COW容器有两种: CopyOnWriteArrayList CopyOnWriteArraySet CopyOnWri ...

  7. HCDA day1

    OSI有几层: OSI将计算机网络体系结构(architecture)划分为以下七层: 图1.OSI模型 物理层: 将数据转换为可通过物理介质传送的电子信号 相当于邮局中的搬运工人. 物理层(Phys ...

  8. Discuptor入门(二)-实例

    前言:最近在项目中看到有人使用的discuptor框架,因为没有接触过所以网上找了些资料.但最终发现开荒者太少,好像没什么人用那.最后感觉还是官方入门文档靠谱点.所以自己翻译了下(翻译器~),希望能帮 ...

  9. JS变量、作用域、内存

    写到这个题目<JS变量.作用域,内存>,我就不由自主想起了黄金三嫖客.可能是名字有点像,嗯,一定是这样子的! JS接触下来,应该是要比Java简单不少的,所以,要学好啊.立个flag半年后 ...

  10. html5手机浏览器启动微信客户端支付实例

    html5手机浏览器启动微信客户端支付实例,外部浏览器html5微信支付技术,如何在手机浏览器微信支付,在微信客户端外的移动端网页使用微信支付 首先在微信支付官网https://pay.weixin. ...