In last Spring auto-wiring in XML example, it will autowired the matched property of any bean in current Spring container. In most cases, you may need autowired property in a particular bean only.

In Spring, you can use @Autowired annotation to auto wire bean on the setter method, constructor or a field. Moreover, it can autowired property in a particular bean.

Note

The @Autowired annotation is auto wire the bean by matching data type.

See following full example to demonstrate the use of @Autowired.

1. Beans

A customer bean, and declared in bean configuration file. Later, you will use “@Autowired” to auto wire a person bean.

package com.mkyong.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.mkyong.common.Customer">
<property name="action" value="buy" />
<property name="type" value="1" />
</bean> <bean id="PersonBean" class="com.mkyong.common.Person">
<property name="name" value="mkyong" />
<property name="address" value="address 123" />
<property name="age" value="28" />
</bean> </beans>

2. Register AutowiredAnnotationBeanPostProcessor

To enable @Autowired, you have to register ‘AutowiredAnnotationBeanPostProcessor‘, and you can do it in two ways :

1. Include <context:annotation-config />

Add Spring context and <context:annotation-config /> in bean configuration file.

<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>

Full example,

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

2. Include AutowiredAnnotationBeanPostProcessor

Include ‘AutowiredAnnotationBeanPostProcessor’ directly in bean configuration file.

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

3. @Autowired Examples

Now, you can autowired bean via @Autowired, and it can be applied on setter method, constructor or a field.

1. @Autowired setter method

package com.mkyong.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 construtor

package com.mkyong.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 field

package com.mkyong.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
}

The above example will autowired ‘PersonBean’ into Customer’s person property.

Run it

package com.mkyong.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[] {"SpringBeans.xml"}); Customer cust = (Customer)context.getBean("CustomerBean");
System.out.println(cust); }
}

Output

Customer [action=buy, type=1,
person=Person [address=address 123, age=28, name=mkyong]]

Dependency checking

By default, the @Autowired will perform the dependency checking to make sure the property has been wired properly. When Spring can’t find a matching bean to wire, it will throw an exception. To fix it, you can disable this checking feature by setting the “required” attribute of @Autowired to false.

package com.mkyong.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
}

In the above example, if the Spring can’t find a matching bean, it will leave the person property unset.

@Qualifier

The @Qualifier annotation us used to control which bean should be autowire on a field. For example, bean configuration file with two similar person 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.mkyong.common.Customer">
<property name="action" value="buy" />
<property name="type" value="1" />
</bean> <bean id="PersonBean1" class="com.mkyong.common.Person">
<property name="name" value="mkyong1" />
<property name="address" value="address 1" />
<property name="age" value="28" />
</bean> <bean id="PersonBean2" class="com.mkyong.common.Person">
<property name="name" value="mkyong2" />
<property name="address" value="address 2" />
<property name="age" value="28" />
</bean> </beans>

Will Spring know which bean should wire?

To fix it, you can use @Qualifier to auto wire a particular bean, for example,

package com.mkyong.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
}

It means, bean “PersonBean1″ is autowired into the Customer’s person property.

Conclusion

This @Autowired annotation is highly flexible and powerful, and definitely better than “autowire” attribute in bean configuration file.

Spring Auto-Wiring Beans with @Autowired annotation的更多相关文章

  1. Spring Auto scanning components

    Normally you declare all the beans or components in XML bean configuration file, so that Spring cont ...

  2. Spring学习(十四)----- Spring Auto Scanning Components —— 自动扫描组件

    一.      Spring Auto Scanning Components —— 自动扫描组件 1.      Declares Components Manually——手动配置componen ...

  3. Spring框架之beans源码完全解析

    导读:Spring可以说是Java企业开发里最重要的技术.而Spring两大核心IOC(Inversion of Control控制反转)和AOP(Aspect Oriented Programmin ...

  4. Spring注解标签详解@Autowired @Qualifier等 @Slf4j

    @Slf4j @Slf4j注解实现日志输出 自己写日志的时候,肯定需要: private final Logger logger = LoggerFactory.getLogger(LoggerTes ...

  5. Spring(3.2.3) - Beans(8): 基于 Annotation 的配置

    除了基于 XML 的配置外,Spring 也支持基于 Annotation 的配置.Spring 提供以下介个 Annotation 来标注 Spring Bean: @Component:标注一个普 ...

  6. Spring Bean依赖但注入(autowired或resource)时NullPointerException(xml和annotation混用的场景下)

    项目中同时使用了xml和annotation的方式管理Spring Bean 启动时候报NullPointerException,依赖注入失败! 参考: http://fly0wing.iteye.c ...

  7. 关于Spring注入参数到static静态参数失败问题处理。解决Autowired annotation is not supported on static fields的问题

    直接贴代码 把注入参数的注解加到set方法上面去即可. 因为这是一个工具类用到的config,所以一开始没有加@Component,还是依然为空,加上之后就正常能注入了

  8. Spring学习(12)--- @Autowired与@Resource 对比

    Spring不但支持自己定义的@Autowired注解,还支持由JSR-250规范定义的几个注解,如:@Resource. @PostConstruct及@PreDestroy. 1. @Autowi ...

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

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

随机推荐

  1. Android下HelloWorld项目的R.java文件介绍

    R.java文件介绍 HelloWorld工程中的R.java文件 package com.android.hellworld; public final class R {     public s ...

  2. Hibernate的一个注释 @Transient

    @Transient表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性. 如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则,ORM框架默认其注解为@Basi ...

  3. WIFI环境下Android手机和电脑通信

    前面已经写过一篇java实现最基础的socket网络通信,这篇和之前那篇大同小异,只是将客户端代码移植到手机中,然后获取本机IP的方法略有不同. 先讲一下本篇中用到Android studio的使用吧 ...

  4. yeoman开始项目

    使用 yeoman 构建项目之前,你需要安装这两个环境:node,ruby. 为什么需要使用node?因为我们需要使用grunt自动化工具,而grunt工具则是依赖node. 为什么需要使用ruby? ...

  5. 【转载】React入门-Todolist制作学习

    我直接看的这个React TodoList的例子(非常好!): http://www.reqianduan.com/2297.html 文中示例的代码访问路径:http://127.0.0.1:708 ...

  6. Android系列之Fragment(一)----Fragment加载到Activity当中

    Android上 的界面展示都是通过Activity实现的,Activity实在是太常用了.但是Activity也有它的局限性,同样的界面在手机上显示可能很好看, 在平板上就未必了,因为平板的屏幕非常 ...

  7. 本来运行的好的Ajax.dll怎么突然不起作用了

    客户中有个好多年前老项目用了Ajax.dll,前几天突然不起作用了. 问了下原因,系统从Windows Server2003 升级为 Windows Server 2008了,IIS也从6升级成7了. ...

  8. UVa 11076 (有重元素的排列) Add Again

    n个可重复的元素的排列一共有 = All种,其中 假设这些数依次为ai,每种数字有mi个. 从右往左考虑第d位数(d≥0),第i个数字出现的次数为,那么这个数字对所求答案的贡献为 其实可以先一次求出个 ...

  9. 浅析Java中HashMap的实现

    概述 HashMap是一个散列表,是基于拉链法实现的.这个类继承了Map接口,Map接口提供了所有的哈希操作,比如set().put().remove()等,并且允许操作的键值对为null.HashM ...

  10. LeetCode Binary Tree Preorder Traversal 先根遍历

    题意:给一棵树,求其先根遍历的结果. 思路: (1)深搜法: /** * Definition for a binary tree node. * struct TreeNode { * int va ...