以下内容引用自http://wiki.jikexueyuan.com/project/spring/annotation-based-configuration/spring-autowired-annotation.html

@Autowired注解提供了在哪里以及如何自动装配应实现更细粒度的控制。@Autowired注解可用于在setter方法上自动连接bean,就像@Required注释,构造函数,属性或具有任意名称和/或多个参数的方法一样。

Setter方法中的@Autowired

您可以在setter方法上使用@Autowired注释来摆脱XML配置文件中的<property>元素。当Spring发现使用setter方法的@Autowired注释时,它会尝试在方法上执行autowire="byType"的自动连接。

例子:

pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.jsoft.testspring</groupId>
<artifactId>testannotationautowired</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>testannotationautowired</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- Spring Core -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <!-- Spring Context -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.4.RELEASE</version>
</dependency>
</dependencies>
</project>

SpellChecker.java:

package com.jsoft.testspring.testannotationautowired;

public class SpellChecker {
public SpellChecker(){
System.out.println("SpellChecker无参数构造函数初始化");
} public void checkSpelling(){
System.out.println("SpellChecker检查方法");
}
}

TextEditor.java:

package com.jsoft.testspring.testannotationautowired;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
private SpellChecker spellChecker;
private String name; @Autowired
public void setSpellChecker(SpellChecker spellChecker){
System.out.println("TextEditor通过setter初始化");
this.spellChecker = spellChecker;
} public void spellCheck() {
this.spellChecker.checkSpelling();
} public void setName(String name){
this.name = name;
} public void getName(){
System.out.println(this.name);
} }

beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <bean id="spellChecker" class="com.jsoft.testspring.testannotationautowired.SpellChecker"></bean> <bean id="textEditor" class="com.jsoft.testspring.testannotationautowired.TextEditor">
<property name="name" value="Hello World!"></property>
</bean> </beans>

此时可以看见textEditor的bean上少了一个<property>标签(元素),但是也能运行正常,因为在TextEditor类中标记了@Autowired的注解,自动匹配去匹配相同类型的bean,与在bean中设置autowire="byType"属性保持一致。

运行结果:

而原始的beans.xml中如下:

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <bean id="spellChecker" class="com.jsoft.testspring.testannotationautowired.SpellChecker"></bean> <bean id="textEditor" class="com.jsoft.testspring.testannotationautowired.TextEditor">
<property name="spellChecker" ref="spellChecker"></property>
<property name="name" value="Hello World!"></property>
</bean> </beans>

属性中的@Autowired

您可以在属性上使用@Autowired注解来摆脱setter方法。当你使用<property>传递自动连线属性的值时,Spring将自动为传递的值或引用分配这些属性。因此,随着@Autowired对属性的使用,您的TextEditor.java文件将如下所示:

package com.jsoft.testspring.testannotationautowired;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
@Autowired
private SpellChecker spellChecker;
private String name; public void spellCheck() {
this.spellChecker.checkSpelling();
} public void setName(String name){
this.name = name;
} public void getName(){
System.out.println(this.name);
} }

可以看出上面代码上SpellChecker的setter方法已经去掉了,而在SpellChecker的私有属性上加入了@Autowired的注解。它会自动创建setter方法。

而beans.xml不需要改变。

运行结果如下:

构造函数中的@Autowired

您也可以将@Autowired应用于构造函数。构造函数@Autowired注解表示构造函数在创建bean时应该是自动连线的,即使在XML文件中配置bean时也不使用<constructor-arg>元素。例子如下:

package com.jsoft.testspring.testannotationautowired;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
private SpellChecker spellChecker;
private String name; @Autowired
public TextEditor(SpellChecker spellChecker){
System.out.println("TextEditor通过初始化方法赋值SpellChecker");
this.spellChecker = spellChecker;
} public void spellCheck() {
this.spellChecker.checkSpelling();
} public void setName(String name){
this.name = name;
} public void getName(){
System.out.println(this.name);
} }

而beas.xml不用改变。

测试结果:

@Autowired的(required=false)选项

默认情况下,@Autowired注解意味着依赖是必须的,它类似于@Required注解,然而,你可以使用@Autowired的(required=false)选项关闭默认行为。例子如下:

package com.jsoft.testspring.testannotationautowired;

import org.springframework.beans.factory.annotation.Autowired;

public class TextEditor {
private SpellChecker spellChecker;
private String name; @Autowired
public TextEditor(SpellChecker spellChecker){
System.out.println("TextEditor通过初始化方法赋值SpellChecker");
this.spellChecker = spellChecker;
} public void spellCheck() {
this.spellChecker.checkSpelling();
} @Autowired(required=false)
public void setName(String name){
this.name = name;
} public void getName(){
System.out.println(this.name);
} }

指定了SpellChecker的setter方法不是必须的,那么也修改beans.xml文件,使其不传入此值。修改后的beans.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <bean id="spellChecker" class="com.jsoft.testspring.testannotationautowired.SpellChecker"></bean> <bean id="textEditor" class="com.jsoft.testspring.testannotationautowired.TextEditor"> </bean> </beans>

测试结果:

测试工程:https://github.com/easonjim/5_java_example/tree/master/springtest/test12/testannotationautowired

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

  1. Spring中@Autowired注解、@Resource注解的区别 (zz)

    Spring中@Autowired注解.@Resource注解的区别 Spring不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource.@ ...

  2. 04 Spring的@Autowired注解、@Resource注解、@Service注解

    什么是注解 传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事务,这么做有两个缺点: 1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分 ...

  3. Spring学习(六)-----Spring使用@Autowired注解自动装配

    Spring使用@Autowired注解自动装配 在上一篇 Spring学习(三)-----Spring自动装配Beans示例中,它会匹配当前Spring容器任何bean的属性自动装配.在大多数情况下 ...

  4. Spring IoC @Autowired 注解详解

    前言 本系列全部基于 Spring 5.2.2.BUILD-SNAPSHOT 版本.因为 Spring 整个体系太过于庞大,所以只会进行关键部分的源码解析. 我们平时使用 Spring 时,想要 依赖 ...

  5. Spring中@Autowired注解、@Resource注解的区别

    Spring不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是@Resource.@PostConstruct以及@PreDestroy. @Resour ...

  6. 转:Spring中@Autowired注解、@Resource注解的区别

    Pay attention: When using these annotations, the object itself has to be created by Spring context. ...

  7. Spring中@Autowired注解与自动装配

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

  8. Spring中Autowired注解,Resource注解和xml default-autowire工作方式异同

    前面说到了关于在xml中有提供default-autowire的配置信息,从spring 2.5开始,spring又提供了一个Autowired以及javaEE中标准的Resource注释,都好像可以 ...

  9. @Resource或者@Autowired作用/Spring中@Autowired注解、@Resource注解的区别

    @Resource或者@Autowired作用不用写set get就能注入,当然,前提是你已经开启了注解功能. spring不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定 ...

随机推荐

  1. Windows下使用python库 curses遇到错误消息的解决方案

    在Windows系统下执行python应用时,有时会遇到错误信息: ModuleNotFoundError: No module named '_curses'. 然而查看Windows系统里pyth ...

  2. bitcoin 源码解析 - 交易 Transaction

    bitcoin 源码解析 - 交易 Transaction(三) - Script 之前的章节已经比较粗略的解释了在Transaction体系当中的整体运作原理.接下来的章节会对这个体系进行分解,比较 ...

  3. feign 负载均衡熔断器

    feign:和zuul配合进行负载均衡. 注解的含义: @EnableDiscoveryClient 声明它是一个资源服务端,即可以通过某些接口调用一些资源: @EnableFeignClients ...

  4. unix网络编程-配置unp.h头文件

    第一步进入:www.unpbook.com,下载unp的随书代码.新建一个目录,将压缩包拷贝到这一目录下面,然后将压缩包直接解压:tar -zxvf  压缩包名.tar.gz 完成上一步后,进入到un ...

  5. zabbix4.2学习笔记系列

    写在前面:对zabbix的接触始于对监控的了解,网上比较多zabbix相关博客,比较多基于3系列甚至2系列,最新开发版zabbix4.2版本已经出来,本博客基于4.2版本学习,参考官网4.2版本和网上 ...

  6. Linux之常用Shell脚本总结

    一.简介本文将总结一些常用的shell脚本,方便以后工作中使用. 二.shell脚本[a]定期备份mysql数据库,需结合cronb定时任务调度实现. #!/bin/bash#首先声明一些自定义变量 ...

  7. 使用Auto Layout中的VFL(Visual format language)——代码实现自动布局

    本文将通过简单的UI来说明如何用VFL来实现自动布局.在自动布局的时候避免不了使用代码来加以优化以及根据内容来实现不同的UI. 一:api介绍 1.NSLayoutConstraint API NSL ...

  8. 13. OPTIMIZER_TRACE

    13. OPTIMIZER_TRACE OPTIMIZER_TRACE表提供由跟踪语句的优化程序跟踪功能生成的信息. 要启用跟踪,请使用optimizer_trace系统变量. 有关详细信息,请参阅M ...

  9. redhat 7.x 、redhat 6.x查看硬盘UUID方法

    1.查看磁盘分区UUID: [root@rac01 ~]# blkid /dev/sdb1: UUID="6bba92c4-0b25-4cc4-9442-ca87c563720a" ...

  10. Python机器学习2.2

    使用Python实现感知器学习算法 在<Python机器学习>中的2.2节中,创建了罗森布拉特感知器的类,通过fit方法初始化权重self.w_,再fit方法循环迭代样本,更新权重,使用p ...