自动装配(autowiring)有助于减少甚至消除配置<property>元素和<constructor-arg>元素,让Spring自动识别如何装配Bean的依赖关系。

自动检测(autodiscovery)比自动装配更进了一步,让Spring能够自动识别哪些类需要被配置成Spring Bean,从而减少对<bean>元素的使用。

1.自动装配属性

1.1  4种类型的自动装配

● byName——把与Bean的属性具有相同名字(或者ID)的其他Bean自动装配到Bean的对应属性中。如果没有跟属性的名字相匹配的Bean,则该属性不进行装配。
      ● byType——把与Bean的属性具有相同类型的其他Bean自动装配到Bean的对应属性中。如果没有跟属性的类型相匹配的Bean,则该属性不被装配。
      ● constructor——把与Bean的构造器入参具有相同类型的其他Bean自动装配到Bean构造器的对应入参中。
      ● autodetect——首先尝试使用constructor进行自动装配。如果失败,在尝试使用byType进行自动装配。

      
      byName自动装配:
<bean id = "kenny" class = "com.ouc.test.springs.Instruments" autowire = "byName" ><property name = "song" value = "bells" />
</bean>

为属性自动装配ID与该属性的名字相同的Bean。

    
     byType自动装配:
    如果Spring寻找到多个Bean,它们的类型与自动装配的属性类型都相匹配,Spring不会猜测哪一个Bean更适合自动装配,而是会抛出异常。
    可以为自动装配标识一个首选Bean,或者可以取消某个Bean自动装配的候选资格。为了使用primary属性,不得不将非首选Bean的primary属性设置为false。
<bean id = "saxophone" class = "com.ouc.test.springs.Saxophone" primary = "false" />

primary属性仅对标识首选Bean有意义。
    如果希望排除某些Bean,可以设置这些Bean的autowire-candidate属性为false。

<bean id = "saxophone" class = "com.ouc.test.springs.Saxophone" autowire-candidate = "false" />

    constructor自动装配:
    如果要通过构造器注入来配置Bean,可以移除<constructor-arg>元素,由Spring在应用上下文中自动选择Bean注入到构造器入参中。
<bean id = "saxophone" class="com.ouc.springs.test.Saxophone"  autowire ="constructor" />

    最佳自动装配:
<bean id = "saxophone" class="com.ouc.springs.test.Saxophone"  autowire ="autodetect" />

1.2 默认自动装配

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsddefault-autowire="byType" ></beans>

2 .使用注解装配

Spring容器默认禁用注解装配。
    启用注解装配最简单的方式是使用Spring的context命名空间配置中的<context:annotation-config>元素。
    Spring 3 支持几种不同的用于自动装配的注解:
     ● Spring自带的@Autowired注解;
     ● JSR-330的@Inject注解;
     ● JSR-250的@Resource注解。

2.1 使用@Autowired

  @Autowiredpublic void setInstrument(Instrument instrument){this.instrument = instrument;}

Spring会尝试对该方法执行byType自动装配,可以使用@Autowired标注需要自动装配Bean引用的任意方法。
     可以使用@Autowired注解直接标注属性,并删除setter方法:

  @Autowiredprivate Instrument instrument;

1)可选的自动装配:
        默认情况下,@Autowired所标注的属性或参数必须是可以装配的。如果没有Bean可以装配到@Autowired所标注的属性或参数中,自动装配就会失败(抛出NoSuchBeanDefinitionException).
        可以通过设置@Autowired的required属性为false来配置自动装配是可选的。

    @Autowired(required=false)private Instrument instrument;

2)限定歧义性的依赖
    @Qualifier注解缩小了自动装配挑选候选Bean的范围,通过指定Bean的ID把选择范围缩小到只剩下一个Bean。

    @Autowired@Qualifier("guitar")private Instrument instrument;

3)创建自定义的限定器(Qualifier)

    import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import org.springframework.beans.factory.annotation.Qualifier;@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Qualifierpublic @interface StringedInstrument{}

2.2 借助@Inject实现基于标准的自动装配

    @Injectprivate Instrument instrument;

@Inject没有required属性。
     限定@Inject所标注的属性。

    @Inject@Named("guitar")private Instrument instrument;

@Named通过Bean的ID来标识可选择的Bean,@Named实际上是一个使用@Qualifier注解所标注的注解。
    创建自定义的JSR-330 Qualifier

    import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import javax.inject.Qualifier;@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Qualifierpublic @interface StringedInstrument{}

2.3 在注解注入中使用表达式

      @Value("#{systemProperties.myFavoriteSong}")private String song;

3.自动检测Bean

使用<context:component-scan>元素配置自动检测。

<?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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.1.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/beans/spring-context-3.1.xsd" ><context:component-scan base-package="com.ouc.springs.test" ></context:component-scan></beans>

3.1为自动检测标注Bean

默认情况下,<context:component-scan>查找使用构造型(stereotype)注解所标注的类,这些特殊的注解如下:
       @Component——通用的构造型注解,标识该类为Spring组件。
       @Controller——标识将该类定义为Spring MVC Controller。
       @Repository——标识将该类定义为数据仓库。
       @Service——标识将该类定义为服务。
        使用@Component标注的任意自定义注解。

3.2 过滤组件扫描

通过为<context:component-scan>配置<context:include-filter>和<context:exclude-filter>子元素,可以随意调整扫描行为。

<context:component-scan base-package="com.ouc.springs.test" ><context:include-filter type="assignable" expression="com.ouc.springs.tst.Instrument" /><context:exclude-filter type="annotation" expression="com.ouc.springs.tst.SkipIt" />
</context:component-scan>

4.使用Spring基于Java的配置

4.1 定义一个配置类

   import org.springframework.context.annotation.Configuration;@Configurationpublic class SpringIdolConfig{}

@Configuration注解会作为一个标识告知Spring:这个类将包含一个或多个Spring Bean的定义。

4.2 声明一个简单的Bean

   @Beanpublic Performer duke(){return new Juggler();}

@Bean告知Spring这个方法将返回一个对象,该对象应该被注册为Spring应用上下文中的一个Bean,方法名将作为该Bean的ID。

转载于:https://www.cnblogs.com/wp5719/p/5136177.html

Spring学习笔记—最小化Spring XML配置相关推荐

  1. 【Spring学习笔记 九】Spring声明式事务管理实现机制

    什么是事务?事务就是把一系列的动作当成一个独立的工作单元,这些动作要么全部完成,要么全部不起作用,关乎数据准确性的地方我们一定要用到事务,防止业务逻辑出错. 什么是事务管理,事务管理对于企业应用而言至 ...

  2. Spring框架学习笔记07:基于XML配置方式使用Spring MVC

    文章目录 一.Spring MVC概述 1.MVC架构 2.Spring MVC 3.使用Spring MVC的两种方式 二.基于XML配置与注解的方式使用Spring MVC (一)创建Spring ...

  3. Spring框架学习笔记09:基于XML配置方式搭建SSM框架实现用户登录

    文章目录 一.采用MVC架构 二.用户登录运行效果 三.基于XML配置方式搭建SSM框架实现用户登录 (一)创建数据库与表 - simonshop (t_user) 1.创建数据库 - simonsh ...

  4. 【Spring学习05】四种xml配置注入方式

    本文博客地址:http://blog.csdn.net/soonfly/article/details/68507615 (转载请注明出处) 平常应用Spring开发中,用得最多的是容器.spring ...

  5. 【Spring学习笔记 四】Spring自动装配机制实践

    我们一般学习某个知识,一定会现有个较为复杂的配置让你理解其中的关系,这个配置清晰规整,但是可能会需要大量的配置,这个时候就会有约定大于配置的理论实现了,通过我们约定好的一致的名称,我可以少写很多对应关 ...

  6. Spring学习笔记之二----基于XML的Spring AOP配置

    在Spring配置文件中,通常使用<aop:config>元素来设置AOP,其中应包括: <aop:aspect>指定aspect,aspect是一个POJO类,包含了很多的a ...

  7. Spring框架学习笔记10:基于XML配置方式SSM框架西蒙购物网

    文章目录 一.网站功能需求 二.网站设计思路 1.设计模式 2.网站前台 3.网站后台 4.购物流程图 三.网站运行效果 四.网站实现步骤 (一)创建数据库与表 1.创建数据库 - simonshop ...

  8. spring学习笔记之配置文件applicationContext.xml

    1:spring中,用配置文件时 <bean>的<scope>属性是singleton时在创建容器时创建对象,创建一个容器在,对象在: <bean>的<sco ...

  9. 【Spring学习笔记-MVC-12】Spring MVC视图解析器之ResourceBundleViewResolver

    场景 当我们设计程序界面的时候,中国人希望界面是中文,而美国人希望界面是英文. 我们当然希望后台代码不需改变,系统能够通过配置文件配置,来自己觉得是显示中文界面还是英文界面. 这是,Spring mv ...

最新文章

  1. 针对JavaScript的常用事件、对象捕获和使用技巧
  2. 解决存储过程中数据安全问题的四种方式
  3. oracle occi出现乱码,linux下occi操作oracle数据库,中文乱码的问题
  4. 报错笔记:cannot convert parameter 1 from 'char [1024]' to 'unsigned char *'
  5. 深度探索C++ 对象模型(6)-Data member的存取
  6. 年月日_C++计算输入的年月日是这一年的第几天
  7. 链式队列的基本操作(入队、出队、遍历队列、清空队列)
  8. C语言实现lu分解lu decompose算法(附完整源码)
  9. velocityjs 动画库 比jquery默认的animate强
  10. from Crypto.Cipher import AES报错
  11. L1-031 到底是不是太胖了 (10 分)—团体程序设计天梯赛
  12. paraview用户指南
  13. ubuntu内存不足时,扩展内存方法(亲测有效)
  14. 关系数据库之关系代数
  15. 【代码开发】neuron_poker安装及简单使用
  16. vb wps 链接单元格_使用VB快速制作WPS的COM加载项
  17. MATLAB小知识(三)——输出矩阵到TXT
  18. 每日一学:洛必达法则及其使用条件
  19. 华为IOT设备消息上报和消息下发验证
  20. 苹果微信更新不了最新版本_教你安卓微信怎么更新到最新版本?

热门文章

  1. 『数据库』数据库系统效率Max--数据库并发控制
  2. 图论--二分图最佳完美匹配(KM模板)
  3. uC/OS-II源码分析(总体思路 三)
  4. 百度贴吧前负责人:做产品16年,我有9条心得[转]
  5. React with Webpack - 3: 内联image、font
  6. HTML MIME Type
  7. 目标检测系列(八)——CenterNet:Objects as points
  8. On the Difference Between Orthogonal Matching Pursuit and Orthogonal Least Squares
  9. yolo opencv_如何使用Yolo,SORT和Opencv跟踪足球运动员。
  10. 尺度空间(Scale space)理论