@Autowired注解可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。

注意:@Autowired默认是按照类型来注入的。

看下面的例子:例子是以对成员变量(field)为例进行的

public class Person {
private String name;
private String address;
private int age; public void setName(String name) {
this.name = name;
} public String getName() {
return name;
} public int getAge() {
return age; } public void setAge(int age) {
this.age = age;
} public void setAddress(String address) {
this.address = address;
} public String getAddress() {
return address;
} @Override
public String toString() {
return "[name:"+getName()+
",address:" + getAddress()+
",age:" +getAge()+
"]";
}

另外一个Customer类有一个Person类型的成员,现用@Autowired注入:

public class Customer
{
@Autowired
private Person person;
private int type;
private String action; public String getAction() {
return action;
} public void setAction(String action) {
this.action = action;
} public int getType() {
return type;
} public void setType(int type) {
this.type = type;
} @Override
public String toString() {
return "[Type:"+getType()+
",action:"+getAction()+
","+"person:"+
person.toString();
}
}

在配置文件中加入

<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">
<!--@Autowired-->
<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>

测试程序:

public class Main
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"SpringBeans.xml"}); Customer customer = (Customer)context.getBean("CustomerBean");
System.out.println(customer);
}
}

@Autowired默认情况下,总是认为field是可以成功注入的,如果没有成功注入(例如没有匹配的类型)则会跑出异常,如果要使得在没有成功注入的情况下不抛出异常,那么可以和required属性一起使用,将required的属性设置为false:

public class Customer
{
**@Autowired(required=false)**
private Person person;
private int type;
private String action;
//getter and setter methods
}

@Autowired默认是按照类型来匹配的,那么当容器中有两个相同类型的bean时怎样区分要注入是哪一个呢?这时候@Qualifier注解便起作用了:

 <bean id="person1" class="com.hzsunpeng.Person">
<property name="name" value="name1"/>
<property name="address" value="adderss1"/>
<property name="age" value="23"/>
</bean>
<bean id="person2" class="com.hzsunpeng.Person">
<property name="name" value="name2"/>
<property name="address" value="adderss2"/>
<property name="age" value="22"/>
</bean>

这时候怎样决定要注入person1呢还是person2呢?

如果想注入person1,那么可以这样做:

public class Customer
{
@Autowired
@Qualifier("person1")
private Person person;
private int type;
private String action;
//setter and getter
}

最后注意一个细节:如果使用了springMVC自动扫描组件(@Component或者是@Service等),在配置文件中加入了

<context:component-scan base-package="***.***.***" />

那么配置文件中的

<context:annotation-config/>

可以省略。

Spring@Autowired注解的更多相关文章

  1. Spring @Autowired 注解 学习资料

    Spring @Autowired 注解 学习资料 网址 Spring @Autowired 注解 https://wiki.jikexueyuan.com/project/spring/annota ...

  2. Spring @Autowired注解用在集合上面,可以保持接口的所有实现类

    CourseService课程接口有2个子类,HistroyCourseServiceImpl和MathsCourseServiceImpl public interface CourseServic ...

  3. Spring @Autowired 注解自动注入流程是怎么样?

    面试中碰到面试官问:"Spring 注解是如果工作的?",当前我一惊,完了这不触及到我的知识误区了吗?,还好我机智,灵机一动回了句:Spring 注解的工作流程倒还没有看到,但是我 ...

  4. Spring@Autowired注解与自动装配

    1   配置文件的方法 我们编写spring 框架的代码时候.一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量.并且要配套写上 get 和 set方法. Boss ...

  5. 【转】Spring@Autowired注解与自动装配

    1   配置文件的方法 我们编写spring 框架的代码时候.一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量.并且要配套写上 get 和 set方法. Boss ...

  6. Spring @Autowired注解在非Controller中注入为null

    问题描述 今天在写一个工具类,里面用了@Autowired注入了StringRedisTemplate以及RedisTemplate时,在template.opsForValue().set(key, ...

  7. Spring@Autowired注解与自动装配(转发)

    1   配置文件的方法 我们编写spring 框架的代码时候.一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量.并且要配套写上 get 和 set方法. Boss ...

  8. [转] Spring@Autowired注解与自动装配

    1   配置文件的方法 我们编写spring 框架的代码时候.一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量.并且要配套写上 get 和 set方法. Boss ...

  9. Spring @Autowired 注解不生效

    @Autowired默认不生效.为了生效,需要在xml配置:<context:annotation-config> 注解一<context:component-scan base-p ...

随机推荐

  1. TCP三次握手原则

    “已失效的连接请求报文段”的产生在这样一种情况下: client发出的第一个连接请求报文段并没有丢失,而是在某个网络结点长时间的滞留了,以致延误到连接释放以后的某个时间才到达server. 本来这是一 ...

  2. [Python] First-class Everything (Python缔造者Guido van Rossum关于bound/unbound method的来历叙述)

    First-class Everything -- Guido van Rossum First-class object: 第一类对象.意指可在执行期创建并作为参数传递给其他函数或存入一个变量的对象 ...

  3. PHP curl登录 跳过验证码

    <?php switch($_GET['do']){ case 'vc': $cookieFile = "./test.tmp"; $url = 'http://localh ...

  4. Qt——布局管理器

    教程地址 运行截图: 代码: #include "mainwindow.h" #include <QApplication> #include <QHBoxLay ...

  5. C语言预处理命令详解

    一  前言 预处理(或称预编译)是指在进行编译的第一遍扫描(词法扫描和语法分析)之前所作的工作.预处理指令指示在程序正式编译前就由编译器进行的操作,可放在程序中任何位置. 预处理是C语言的一个重要功能 ...

  6. PON系统基础知识简介

    一  PON基础知识 1.1 PON技术概念 PON(Passive Optical Network)即无源光网络,一种基于点到多点(P2MP)拓朴的技术.“无源”指ODN(光分配网络)不含有任何电子 ...

  7. 【Laravel5.5】 laravel5 数据库配置(MySQL)

    1   进入laravel根目录.      在config目录下找到database.php文件.      显而易见这个文件是数据库相关的配置文件. 2  修改 .env 配置完database. ...

  8. Qt编写输入法终极版V2018

    输入法是很多Qt+嵌入式linux开发的同学的痛,自从5.7自带了输入法后,这个痛终于缓解了不少,不过还有大量的嵌入式linux程序停留在qt4时代,为此特意选择了QWidget来写这个输入法,为了兼 ...

  9. C# 中对COOKIES的操作

    HttpUtility.UrlDecode HttpUtility.UrlEncode HttpContext.Current.Request.Cookies["UserCode" ...

  10. nginx 启动重启脚本

    #! /bin/sh # Default-Start:     2 3 4 5 # Default-Stop:      0 1 6 # Short-Description: starts the n ...