Spring Auto-Wiring Beans with @Autowired annotation
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的更多相关文章
- Spring Auto scanning components
Normally you declare all the beans or components in XML bean configuration file, so that Spring cont ...
- Spring学习(十四)----- Spring Auto Scanning Components —— 自动扫描组件
一. Spring Auto Scanning Components —— 自动扫描组件 1. Declares Components Manually——手动配置componen ...
- Spring框架之beans源码完全解析
导读:Spring可以说是Java企业开发里最重要的技术.而Spring两大核心IOC(Inversion of Control控制反转)和AOP(Aspect Oriented Programmin ...
- Spring注解标签详解@Autowired @Qualifier等 @Slf4j
@Slf4j @Slf4j注解实现日志输出 自己写日志的时候,肯定需要: private final Logger logger = LoggerFactory.getLogger(LoggerTes ...
- Spring(3.2.3) - Beans(8): 基于 Annotation 的配置
除了基于 XML 的配置外,Spring 也支持基于 Annotation 的配置.Spring 提供以下介个 Annotation 来标注 Spring Bean: @Component:标注一个普 ...
- Spring Bean依赖但注入(autowired或resource)时NullPointerException(xml和annotation混用的场景下)
项目中同时使用了xml和annotation的方式管理Spring Bean 启动时候报NullPointerException,依赖注入失败! 参考: http://fly0wing.iteye.c ...
- 关于Spring注入参数到static静态参数失败问题处理。解决Autowired annotation is not supported on static fields的问题
直接贴代码 把注入参数的注解加到set方法上面去即可. 因为这是一个工具类用到的config,所以一开始没有加@Component,还是依然为空,加上之后就正常能注入了
- Spring学习(12)--- @Autowired与@Resource 对比
Spring不但支持自己定义的@Autowired注解,还支持由JSR-250规范定义的几个注解,如:@Resource. @PostConstruct及@PreDestroy. 1. @Autowi ...
- Spring学习(9)--- @Autowired注解(二)
可以使用@Autowired注解那些众所周知的解析依赖性接口,比如:BeanFactory,ApplicationContext,Environment,ResourceLoader,Applicat ...
随机推荐
- [Codeforces673A]Bear and Game(水题,思路)
题目链接:http://codeforces.com/contest/673/problem/A 题意:一个人看一个90分钟的节目,然后告诉你一些有趣的时刻.这个人假如在15分钟内还没有看到有趣的时刻 ...
- 好!recover-binary-search-tree(难)& 两种好的空间O(n)解法 & 空间O(1)解法
https://leetcode.com/mockinterview/session/result/xyc51it/https://leetcode.com/problems/recover-bina ...
- UVa 12230 (期望) Crossing Rivers
题意: 从A到B两地相距D,之间有n段河,每段河有一条小船,船的位置以及方向随机分布,速度大小不变.每段河之间是陆地,而且在陆地上行走的速度为1.求从A到B的时间期望. 分析: 我们只要分析每段河的期 ...
- BZOJ 3166 Alo
处理出每个数最靠近它的左右两个比它大的数. 然后可持久化trie. #include<iostream> #include<cstdio> #include<cstrin ...
- UVA 1395 Slim Span (最小生成树,MST,kruscal)
题意:给一个图,找一棵生成树,其满足:最大权-最小权=最小.简单图,不一定连通,权值可能全相同. 思路:点数量不大.根据kruscal每次挑选的是最小权值的边,那么苗条度一定也是最小.但是生成树有多棵 ...
- 聚焦 SQL 数据库活动异地复制
Tobias Ternstrom US-DS-PM 首席部门项目经理 本文作为一系列业务连续性和灾难恢复文章的开篇,概述了业务连续性的各种场景,然后重点介绍 SQL 数据库高级服务级别提供的活动异地 ...
- svn - 常用命令
基本流程: 获取新的代码,svn up(date),获取最新代码 锁住文件,防止你提交的时候,别人修改,造成冲突,svn lock filename 修改之后,svn add filename,将文件 ...
- LeetCode:Sort List
Title: Sort a linked list in O(n log n) time using constant space complexity. 思路:考虑快速排序和归并排序,但是我的快速排 ...
- .Net中的各种序列化
我们知道将对象的状态保持在存储媒体中,以便可以在以后重新创建精确的副本这正是数据持久化所要做的.而且,不同应用程序之间的通讯需要相互传输数据.那么序列化和反序列化正是为此而生. 序列化和反序列化 所谓 ...
- Jedis的Sharded源代码分析
概述 Jedis是Redis官方推荐的Java客户端,更多Redis的客户端可以参考Redis官网客户端列表.当业务的数据量非常庞大时,需要考虑将数据存储到多个缓存节点上,如何定位数据应该存储的节点, ...