自动装配(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/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
default-autowire="byType" >
</beans>

2 .使用注解装配

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

2.1 使用@Autowired

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

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

  @Autowired
private 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)
@Qualifier
public @interface StringedInstrument{}

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

    @Inject
private 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)
@Qualifier
public @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/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://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;

   @Configuration
public class SpringIdolConfig{}

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

4.2 声明一个简单的Bean

   @Bean
public Performer duke(){
return new Juggler();
}

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

Spring学习笔记—最小化Spring XML配置的更多相关文章

  1. Spring 学习笔记(四)—— XML配置依赖注入

    依赖注入(DI)与控制反转(IoC)是同一个概念,都是为了处理对象间的依赖关系. 通过DI/IoC容器,相互依赖的对象由容器负责创建和装配,而不是在代码中完成. Spring支持通过setter方法和 ...

  2. 【Spring学习笔记-MVC-15】Spring MVC之异常处理

    作者:ssslinppp       1. 描述 在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的.不可预知的异常需要处理 ...

  3. Spring学习笔记五:Spring进行事务管理

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6776256.html  事务管理主要负责对持久化方法进行统一的提交或回滚,Spring进行事务管理即我们无需在 ...

  4. struts2视频学习笔记 22-23(基于XML配置方式实现对action的所有方法及部分方法进行校验)

    课时22 基于XML配置方式实现对action的所有方法进行校验   使用基于XML配置方式实现输入校验时,Action也需要继承ActionSupport,并且提供校验文件,校验文件和action类 ...

  5. spring学习笔记 星球日one - xml方式配置bean

    ide: idea lib包的导入:http://webcache.googleusercontent.com/search?q=cache:http://zyjustin9.iteye.com/bl ...

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

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

  7. Spring学习笔记:jdbcTemplate和数据源配置

    一.使用Spring框架jdbcTemplate实现数据库的增删改查 1.数据库 /* SQLyog Ultimate v8.32 MySQL - 5.7.19-log : Database - in ...

  8. spring学习笔记(22)声明式事务配置,readOnly无效写无异常

    在上一节内容中.我们使用了编程式方法来配置事务,这种优点是我们对每一个方法的控制性非常强.比方我须要用到什么事务,在什么位置假设出现异常须要回滚等.能够进行非常细粒度的配置.但在实际开发中.我们可能并 ...

  9. Spring学习笔记之六(数据源的配置)

    1.前言 上一篇博客分析了,Spring中实现AOP的两种动态代理的机制,以下这篇博客.来解说一下Spring中的数据源的配置.  2.DAO支持的模板类 Spring提供了非常多关于Dao支持的模板 ...

随机推荐

  1. sqlite采用的ORM包

    关注了两个库的使用方式,一个是Dapper,一个是Simple.Data.考虑一个可选的是ORMLite, Dapper和simple.data都比较好用,动态对象的使用妙不可言,区别在于 //Dap ...

  2. HTTP及状态码汇总

    什么是HTTP: HTTP(HyperText Transfer Protocol超文本传输协议)是互联网上应用最为广泛的一种网络协议.所有的WWW文件都必须遵守这个标准,为了提供一种发布和接收HTM ...

  3. 跟着百度学PHP[4]OOP面对对象编程-8-继承

    如下图所示.人就是父类!而NBA球员以及女主播就是子类 要继承一个类,那么在类名的后面加上extends 要继承的类名 具体格式:class Student extends human{}     # ...

  4. Linux之Shell的算术运算

    在Bash的算术运算中有以下几种方法:名称                语法                    范例算术扩展            $((算术式))              r ...

  5. Android 趣味应用—— 短信编辑器

    修改短信数据库,从而生成任意手机号发送的短信. AndroidManifest.xml <?xml version="1.0" encoding="utf-8&qu ...

  6. Java WebClient 总结

    private WebClient getAWebClient() { WebClient webClient = new WebClient(BrowserVersion.FIREFOX_24); ...

  7. @PathVariable注解

    spring mvc中的@PathVariable是用来获得请求url中的动态参数的,十分方便,复习下: . @Controller public class TestController { @Re ...

  8. java面试宝典(蓝桥学院)

    Java面试宝典(蓝桥学院) 回答技巧 这套面试题主要目的是帮助那些还没有java软件开发实际工作经验,而正在努力寻找java软件开发工作的学生在笔试/面试时更好地赢得好的结果.由于这套试题涉及的范围 ...

  9. Node.JS初识

    对Node.JS的认识 1.Node 是一个服务器端 JavaScript 解释器: 2.Node 的目标是帮助程序员构建高度可伸缩的应用程序,编写能够处理数万条同时连接到一个物理机的连接代码.处理高 ...

  10. SQL Server 2005中的分区表

    记录笔记: 转自 猪八戒学做网站 SQL Server 2005中的分区表(一):什么是分区表?为什么要用分区表?如何创建分区表? SQL Server 2005中的分区表(二):如何添加.查询.修改 ...