Spring 系列教程


自动装配

前面介绍了使用<constructor-arg><property>注入依赖项,我们还可以使用自动装配的方式实现依赖注入,大大减少配置编写。

自动装配通过以下方式查找依赖项:

  • byName: 通过属性名。匹配类中的属性名和xml中依赖bean id。
  • byType: 通过属性数据类型。匹配类中的属性数据类型和依赖bean类型,如果可以匹配多个bean,则抛出致命异常。
  • constructor: 通过构造函数参数的数据类型。匹配构造函数参数的数据类型和依赖bean类型,如果容器中没找到类型匹配的Bean,抛出致命异常。

自动装配示例:

public class App {

    private Service mainService;
private Service[] services; // 注入Service实例
public App(Service main){
this.mainService = main;
} // 注入Service实例数组
public App(Service[] services){
this.services = services;
} public Service getMainService() {
return mainService;
} // 通过setter方法注入服务实例
public void setMainService(Service mainService) {
this.mainService = mainService;
} public Service[] getServices() {
return services;
} // 通过setter方法注入服务实例数组
public void setServices(Service[] services) {
this.services = services;
}
}

xml配置:

<bean id="app" class="App" autowire="byType"></bean>

依赖项数组可通过byType/constructor自动装配。使用byType/byName,Java类必须实现setter方法。

使用byType/constructor,可能有多个Bean匹配,可通过设置autowire-candidate="false"去除匹配。

示例:

<bean id="app" class="App" autowire="byType"></bean>
<bean id="database" class="Database" autowire-candidate="false"></bean>
<bean id="mail" class="Mail" autowire-candidate="false"></bean>
<bean id="logger" class="Logger" autowire-candidate="true"></bean>

使用byName,如下所示会自动装配mainService,App类中的属性mainService<bean id="mainService"匹配:

<bean id="app" class="App" autowire="byName"></bean>
<bean id="database" class="Database"></bean>
<bean id="mail" class="Mail"></bean>
<bean id="mainService" class="Logger"></bean>

自动装配的局限性

  • 被覆盖的可能性: 仍可通过<constructor-arg><property>配置覆盖自动装配的配置。
  • 不支持原始数据类型: 原始数据类型的值不能通过自动装配的方式注入。
  • 不够精准: 自动装配不如手动装配精准,尽量使用手动装配。

最新文章

  1. 【C#进阶系列】23 程序集加载和反射
  2. 上传github代码
  3. 关于初学者Could not find action or result :No result defined for action com.lyw.action.LoginAction and result success
  4. curl operate elasticsearch
  5. Nginx支持多站点配置小结
  6. php获取json文件数据并动态修改网站头部文件meta信息 --基于CI框架
  7. error: Error retrieving parent for item: No resource found that matches the given name &amp;#39;Theme.AppCompat.Light&amp;#39;.,appcompatv7
  8. Qt之QHeaderView自定义排序(终极版)
  9. mysql innodb 数据打捞(二)innodb 页面打捞编程
  10. 一步步学习ASP.NET MVC3 (11)——@Ajax,JavaScriptResult(2)
  11. 指令-arContentedit-可编辑的高度自适应的div
  12. Software Engineering-HW2
  13. 【ElasticSearch篇】--ElasticSearch从初识到安装和应用
  14. Spark之谓词下推
  15. 修改JDK版本配置
  16. centos7_ linux : Nginx安装手册
  17. 个人博客作业Week2 是否需要有代码规范
  18. matplotlib fill和fill_between
  19. python 全栈开发,Day100(restful 接口,DRF组件,DRF跨域(cors组件))
  20. chrome浏览器的跨域设置 Google Chrome浏览器下开启禁用缓存和js跨域限制--disable-web-security

热门文章

  1. pyhton的返回值
  2. 代理实现aop以及代理工厂实现增强
  3. day14-Python运维开发基础(内置函数、pickle序列化模块、math数学模块)
  4. Caused by: java.net.ConnectException: Connection timed out: connect
  5. 在Java中,为什么十六进制数0xFF取反之后对应的十进制数是-256呢?
  6. 102、Java中String类之相等判断(忽略大小写)
  7. 5.4 Linux 安装2个tomcat
  8. MySQL 加密 压缩
  9. LR_问题_平均响应时间解释,summary与analysis不一致----Summary Report中的时间说明
  10. vld扩展