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. programming-languages学习

    programming-languages学习 */--> pre.src {background-color: #292b2e; color: #b2b2b2;} pre.src {backg ...

  2. QTP基本方法3-----截屏

    1.桌面截屏 Desktop.captureBitMap  path[,bolean] path:保存路径,可选择绝对路径或相对路径 相对路径是保存在脚本保存的目录下编号最大的res目录下. bole ...

  3. javascript-对象搜索算法挑战

    对象搜索算法挑战 function where(collection, source) { var arr = []; var status = null; // What's in a name? ...

  4. .NET Core中基类可以反射子类的成员

    我们定义一个类DemoA,再定义一个类DemoB继承DemoA.当构造一个DemoB类对象后,我们可以通过其调用基类DemoA中的方法来反射子类DemoB的成员. 新建一个.NET Core控制台项目 ...

  5. 【PTA 天梯赛】L1-046 整除光棍(除法模拟)

    这里所谓的“光棍”,并不是指单身汪啦~ 说的是全部由1组成的数字,比如1.11.111.1111等.传说任何一个光棍都能被一个不以5结尾的奇数整除.比如,111111就可以被13整除. 现在,你的程序 ...

  6. 同步工具类-----循环栅栏:CyclicBarrier

    import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; impor ...

  7. MySQL数据查询(重点)

    1.查询所有列   * 为所有列 select * from table_name; 2.查询指定列 select id,age from table_name; 3.查询时添加常量列-------本 ...

  8. spring定时任务注解@Scheduled的记录

    spring 定时任务@Scheduled 转自https://www.cnblogs.com/0201zcr/p/5995779.html 1.配置文件 <?xml version=" ...

  9. 学习ThinkPHP5的第一天(安装 连接数据库)

    参考文档:thinkPHP5.0完全手册  一.安装 采用的是git安装方式: 应用项目:https://github.com/top-think/think 核心框架:https://github. ...

  10. laravel5.5源码阅读草稿——路由

    laravel 里的路由是由RouteServiceProvider提供的,其中的boot方法为启动项,调用了父类的boot方法. RouteServiceProvider中的boot方法设置了自己与 ...