博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring(四)Spring之自动装配(autowire)
阅读量:7100 次
发布时间:2019-06-28

本文共 2128 字,大约阅读时间需要 7 分钟。

什么是自动装配?

spring IOC容器可以自动装配(autowire)相互协作bean之间的关联关系。因此,如果可能的话,可以自 动让Spring通过检查BeanFactory中的内容,来替我们指定bean的协作者(其他被依赖的bean)。由于 autowire可以针对单个bean进行设置,因此可以让有些bean使用autowire,有些bean不采用。autowire的 方便之处在减少或者消除属性或构造器参数的设置,这样可以给我们的配置文件减减肥 在配置文件中给域属性注入值时除了使用

(外面的bean节点我没有写,在前面已经有写过,在这里简单提一下)

还有一种方法就是域属性自动装配设置bean节点中的autowire属性来给他注入值

下面用个例子来说一下

首先是准备工作

先创建两个类Student和Car,类中的内容如下

package demo06;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import javax.annotation.Resource;/** * Created by mycom on 2018/3/5. */public class Student {    private String name;    private Integer age;    private Car car;    public Student() {    }    public Student(String name, Integer age) {        this.name = name;        this.age = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }    public Car getCar() {        return car;    }    public void setCar(Car car) {        this.car = car;    }}
package demo06;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;/** * Created by mycom on 2018/3/5. */public class Car {    private String color;    private String brand;    public String getBrand() {        return brand;    }    public void setBrand(String brand) {        this.brand = brand;    }    public String getColor() {        return color;    }    public void setColor(String color) {        this.color = color;    }}

在配置文件中进行配置

在这里说明一下:

autowire的值有两个 byName和byType 

byName就是根据Spring管理的Car的id值来进行属性注入

byType 就是根据Spring管理的Car的类型注入,所以这种注入方式有两种

 

转载于:https://www.cnblogs.com/my-123/p/8521735.html

你可能感兴趣的文章
python正则提取关键字
查看>>
php 中 set_time_limit 理解
查看>>
28 写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作(进阶)...
查看>>
MHA切换过程:
查看>>
HanLP汉语言分析框架
查看>>
SQLite 日期操作
查看>>
热词分享
查看>>
phpcms相关
查看>>
thinkphp空控制器的处理
查看>>
Unity优化----drawcall系列
查看>>
通过按键实现LED灯的亮灭(含两种情况)
查看>>
C#中常用接口介绍
查看>>
swift 纯代码自定义控件
查看>>
使用Groovy的sql模块操作mysql进行多种查询
查看>>
解决mysql 主从数据库同步不一致的方法
查看>>
字符编码笔记:ASCII,Unicode 和 UTF-8
查看>>
Stack
查看>>
[BZOJ3631][JLOI2014]松鼠的新家(树链剖分)
查看>>
libgdx游戏引擎开发笔记(四)文字显示BitmapFont
查看>>
JavaScript和Webservice实现联动
查看>>